Java: Retrieving an element from a HashSet

Viewed 265910

Hoping someone can explain why I cannot retrieve an element from a HashSet.

Consider my HashSet containing a list of MyHashObjects with their hashCode() and equals() methods overridden correctly.

What I was hoping to do was to construct a MyHashObject myself, and set the relevant hash code properties to certain values. I can query the HashSet to see if there "equivalent" objects in the set using the contains() method. So even though contains() returns true for the 2 objects, they may not be == true.

How come then there is no get() method similar to how the contains() works?

Interested to know the thinking behind this API decision

10 Answers

First of all convert your set to Array. Then, get item by index of array .

Set uniqueItem = new HashSet() ;
uniqueItem.add("0");
uniqueItem.add("1");
uniqueItem.add("0");

Object[] arrayItem = uniqueItem.toArray(); 
for(int i = 0; i < uniqueItem.size();i++){
    System.out.println("Item "+i+" "+arrayItem[i].toString());
}

One of the easiest ways is to convert to Array:

for(int i = 0; i < set.size(); i++) {
    System.out.println(set.toArray()[i]);
}

If you want to have a reference to the real object using the same performance as HashSet, I think the best way is to use HashMap.

Example (in Kotlin, but similar in Java) of finding an object, changing some field in it if it exists, or adding it in case it doesn't exist :

val map = HashMap<DbData, DbData>()
val dbData = map[objectToFind]
if(dbData!=null){
  ++dbData.someIntField
}
else {
  map[dbData] = dbData
}
Related