0

I am facing a problem while writing my code. I am using HashSet in java.
I have the requirement that if a object does not exist in hashset, then add that particular object using add() method.

But if the object already exists, I need that particular object to save somewhere else. But I don't see get() method for hashset in java. Could someone please help?

Is there any way to get the object from HashSet or please suggest some other data structure.

3 Answers3

1

An example of retrieving an object contained in a HashSet might be

    HashSet<String> hSet = new HashSet<String>();
    hSet.add("XXX");

    Iterator iter = hSet.iterator();
    while(iter.hasNext()){

    String obj = (String)iter.next();
    System.out.println(obj);
    }

It outputs XXX

dsp_user
  • 2,061
  • 2
  • 16
  • 23
  • Hi, using the iterator, we can get get objects stored one by one. My requirement is that I have a clone of one of the objects in my data and I need to extract only that object in minimum possible time. – Ashish Goyal Jan 12 '16 at 11:40
  • I don't understand. If you already have a clone (a copy) of an object, why not just use that object. Sorry, you really need to explain better your requirements. – dsp_user Jan 12 '16 at 13:00
  • My requirement is to minimize space. I have limited objects but millions of reference to them. I will store all those object in HashSet. So, I can't create new object for each reference. I will just refer to the same object again and again. I hope its clear now. – Ashish Goyal Jan 12 '16 at 16:29
  • Could you provide some code because I'm still none the wiser. If the references are not null , then you already have objects. – dsp_user Jan 12 '16 at 21:02
  • // Let me try. HashSet stringSet = new HashSet<>(); stringSet.add("A"); stringSet.add("B"); // and so on many strings // Now I have a list of list of strings which point to strings from this set. List> myData = new ArrayList>; // Now assume, i have to refer to both the strings for each entry for(int i=0; i tempList = new ArrayList<>(); tempList.add(new String("A")); tempList.add(new String("B")); myData.add(tempList); } – Ashish Goyal Jan 13 '16 at 05:44
  • You have to copy above code into notepad++. I dont know how to format that. Here you can observe that though we only need to create two string and in my app refer to them. But ultimately, I am creating too many objects. This is just a sample code but actual need is similar to that – Ashish Goyal Jan 13 '16 at 05:47
  • It's not clear to me (and I don't think it would be clear to anybody ) what you want to achieve with that code. How exactly do you need to use the strings stored in the set? – dsp_user Jan 13 '16 at 07:47
0

To check if the object is already present in the set You can use the method contains of interface Collection.

Or simply add it and check the return value of add. (see add documentation for details)

if (set.add(myObject)) {
    // Added
} else {
    // Not added because it was already present
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Not sure why this correct answer was downvoted - especially the hint to the return value from `add` should be useful for the OP, since it allows to simply save his object "somewhere else" in the `else` branch – Andreas Fester Jan 11 '16 at 11:22
0

You could use a HashMap<YourClass,YourClass>.

YourClass yourClassKey = ...;
YourClass obj = map.get(yourClassKey); // if a key equal to yourClassKey is in the map,
                                       // you get the existing object from the map 
if (obj == null) { // if yourClassKey is not in the map, you add it
    map.put(yourClassKey,yourClassKey);
    obj = yourClassKey;
}

BTW, using a HashMap instead of a HashSet won't require more memory, since HashSet uses a HashMap internally anyway.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Why using a Map? He has not explained that an object can be retrieved by key. Instead of using an HashMap with key and value of the same class (and same values) is better to use an HashSet. It works internally as a Map but it doesn't store a reference to a couple (key, value). – Davide Lorenzo MARINO Jan 11 '16 at 11:19
  • @DavideLorenzoMARINO The OP want's the original object from the data structure. The `Set` interface only tells you if an object equal to what you are looking for is in the Set, it doesn't return the actual object, which is what the OP asked for. – Eran Jan 11 '16 at 11:21
  • I suppose that he asked for the get method not knowing that exists the contains method. Should be understood if " that particular object " is the object saved on the set or can be the parameter used to check the presence – Davide Lorenzo MARINO Jan 11 '16 at 11:25
  • @DavideLorenzoMARINO I assumed that the OP knows `Set` has a `contains` method, since the OP looked at the interface long enough to notice there is no `get` method. If the OP doesn't need to retrieve the instance already in the HashSet, using `contains` would be the trivial solution. – Eran Jan 11 '16 at 11:28
  • @Eran, David : Thanks both of you. Actually I know about contains methods but Eran understood it correctly. I need to get the original object from the set and some other reference with refer to this. That way, I am saving memory by creating just one object and referring it from multiple place. Memory is precious as per my project requirement. – Ashish Goyal Jan 12 '16 at 11:30
  • @Eran : Yes, I am using map for now as you mentioned using same object as key and value. In this case, I have only one object per entry but there are two references(key and value). So, I was wondering if I could save the memory used by duplicated references. – Ashish Goyal Jan 12 '16 at 11:31
  • @Asish As I mentioned in my answer, using a HashMap instead of HashSet does not require more memory, since HashSet uses a backing HashMap for its storage, where the key is the HashSet's element and the value a reference to a dummy object. Therefore there's no need to worry about the additional references used for the HashMap's values. – Eran Jan 12 '16 at 12:15
  • @Eran : Thanks for your reply. I also looked at HashSet implementation. Yeah, that uses map internally. Is there a better way to do it apart from what we discussed? – Ashish Goyal Jan 12 '16 at 16:32