Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in Java Collection between JDK 6 and JDK8

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.

like image 871
Khalifa Avatar asked Jan 02 '23 18:01

Khalifa


2 Answers

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.

like image 87
Eugene Avatar answered Feb 11 '23 22:02

Eugene


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).

like image 22
Eran Avatar answered Feb 11 '23 22:02

Eran