eljenso - 6 months ago 22x

Java Question

If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed to be identical for every identical set of elements added, *irrespective* of the order in which they were added?

Bonus question: what if the insertion order is identical as well?

(Assuming Sun JDK6 with same HashSet initialization.)

**Edit:** My original question was not clear. It is not about the general contract of HashSet, but what Sun's implementation of HashSet in JDK6 offers as guarantees concerning determinism. Is it inherently non-deterministic? What influences the order used by its Iterator?

Answer

Absolutely not.

The insertion order directly influences the iteration order whenever you have a bucket collision:

When two elements end up in the same bucket, the first one that was inserted will also be the first one returned during iteration, at least if the implementation of collision handling and iteration is straightforward (and the one in Sun's `java.util.HashMap`

is)

Source (Stackoverflow)

Comments