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.
The implementation did change, but who cares? You are dealing with a HashSet
that documents as having no order to rely-on. So simply printing, is not doing anything, just showing that all elements are there.
In java-9 Set#of
and Map#of
(the new collections) have no defined order from run-to-run for example. No order defined == do not rely on it.
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 the HashSet
will 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:
Set<String> types = new LinkedHashSet<String>();
String result;
types.add("BLA");
types.add("TEST");
System.out.println (types);
will print
[BLA, TEST]
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
's toString()
(which is the implementation HashSet
and LinkedHashSet
use) lists the elements in the order they are returned by the iterator.
String java.util.AbstractCollection.toString()
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With