I was wondering if the implementation of java.util.collections has changed between Java 6 and Java 8. I have this test that works fine in Java 6 but not in Java 8
Set<String> types = new HashSet<String>();
String result;
types.add("BLA");
types.add("TEST");
The result in Java 6 : [BLA, TEST] The result in Java 8 : [TEST, BLA] I already looked in the documentation and release notes of JDK 7 and JDK 8 but didn't find any difference between JDK 6 and the two others concerning this. Thanks in advance for the clarifications.
You have no reason to expect the
[BLA, TEST]output in either JDK6 or JDK8, since the Javadoc doesn't promise you the elements of theHashSetwill be printed according to insertion order (or any order). Different implementations are allowed to produce different order.If you want to ensure that output in both JDKs, use a
LinkedHashSet, which maintains insertion order:will print
in both versions.
By the way, this output is not guaranteed by the Javadoc either, so it can be considered as an implementation detail that may change in future versions, but's it's less likely to change. The reason for this output is that
AbstractCollection'stoString()(which is the implementationHashSetandLinkedHashSetuse) lists the elements in the order they are returned by the iterator.