Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration order of HashSet

Tags:

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?

like image 759
eljenso Avatar asked Apr 24 '10 13:04

eljenso


People also ask

What is the order of HashSet?

It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.

Can you iterate through a HashSet?

There are three simple ways to iterate over a HashSet, which is the following : Using Iterator. Without using Iterator (using for loop) Using for-each loop.

Is HashSet in Java ordered?

No. HashSet is not ordered.

Does HashSet follow insertion order?

HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements.


1 Answers

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)

like image 84
Michael Borgwardt Avatar answered Sep 22 '22 12:09

Michael Borgwardt