Why cannot I retrieve an element from a HashSet?
Consider my HashSet containing a list of MyHashObjects with their hashCode() and equals() methods overridden correctly. I was hoping 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 two objects, they may not be == true.
How come then there isn’t any get() method similar to how the contains() works?
What is the thinking behind this API decision?
If you know what element you want to retrieve, then you already have the element. The only question for a Set to answer, given an element, is whether it
contains()it or not.If you want to iterator over the elements, just use a
Set.iterator().It sounds like what you’re trying to do is designate a canonical element for an equivalence class of elements. You can use a
Map<MyObject,MyObject>to do this. See this Stack Overflow question or this one for a discussion.If you are really determined to find an element that
.equals()your original element with the constraint that you must use theHashSet, I think you’re stuck with iterating over it and checkingequals()yourself. The API doesn’t let you grab something by its hash code. So you could do:It is brute-force and O(n) ugly, but if that’s what you need to do…