The question really is regarding objects that change dynamically in a collection. Does the “contains” method go and compare each of the object individually every time or does it do something clever?
If you have 10000 entries in a collection, I would have expected it to work a bit more cleverly but not sure. Or if not is there a way to optimise it by adding a hook that would tell the collection object to update hashcodes for the objects that have changed??
Additional Question:
Thanks for answers below… Can I also ask what happens in case of ArrayList? I could not find anything in the documentation that says not to put mutable objects in ArrayList. Does that mean the search algorithm simply goes and compares against hashcode of each object??
The simple answer is — no, nothing clever happens. If you expect an object’s state to change in a way that affects its
hashCode()andequals(...)behavior, then you must not store it in aHashSet, nor any otherSet. To quote from http://download.oracle.com/javase/6/docs/api/java/util/Set.html: