I have overriden equals
and hashCode
for a custom object Foo
. Now, I have the hash code of an object and would like to check if the object is contained in the Set<Foo> fooSet
. Is there a more efficient way to search for it other than
for(Foo o : fooSet) {
if(o.hashCode == inputCode) {
return true;
}
}
You basically can't determine it reliably based on a hash code. You can check that a value definitely isn't in the set, but even if you find a matching hash code that doesn't mean that the value is in the set. This is rarely useful, which is why there's nothing which exposes the functionality within Set
. I don't know of any faster way of achieving this half-result. (Note that if you've just got a Set
rather than a HashSet
, there may well be nothing in the internal data structures which has recorded hash codes anyway...)
If you really only care about the presence of a hash code, just store a Set<Integer>
instead of the full set. But it's not terribly useful to do so, usually.
See more on this question at Stackoverflow