Reputation: 10028
I'm trying to learn the concept of Set interface and HashSet class in java. I have read
when using HashSet class, that there is no guarantee of the sequence of elements when I iterate over.
I have came up with some code and run ten times and it always iterate in the order of insertion. So is this due to luck?
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Iterator i1 = set1.iterator();
while (i1.hasNext()){
System.out.println(i1.next());
}
Upvotes: 2
Views: 414
Reputation: 9287
YES. It's due to "luck". It depends on the JRE implementation! I learned this the hard way many years ago when started implementing in Java, and the code was tested on different platforms.
If i recall, in windows a HashSet iteration was perfectly ordered, but in Mac OSX totally scrambled!
Bottom line: Always rely on the docs, and not on the apparent results!
Upvotes: 2
Reputation: 4135
As per the javadoc:
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. [...] The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created
From Java4
we have LinkedHashSet
which guarantees that the iteration order and the insertion order is same.
Upvotes: 2