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, which works fine in Java 6, but not in Java 8

Set<String> types = new HashSet<String>();
String result;
types.add("BLA");
types.add("TEST");

Result in Java 6: [BLA, TEST] Result in Java 8: [TEST, BLA] I already looked through the documentation and release notes for JDK 7 and JDK 8, but I did not find the difference between JDK 6 and the other two regarding it. Thanks in advance for clarification.

+4
source share
2 answers

You have no reason to expect output [BLA, TEST]in JDK6 or JDK8, because Javadoc does not promise that the elements HashSetwill be printed in the insertion order (or any order). Different implementations allow the creation of a different order.

JDK, LinkedHashSet, :

Set<String> types = new LinkedHashSet<String>();
String result;
types.add("BLA");
types.add("TEST");
System.out.println (types);

[BLA, TEST]

.

, Javadoc, , , . , AbstractCollection toString() ( HashSet LinkedHashSet) , .

java.util.AbstractCollection.toString()

. , , ( "[]" ). "," ( ). , String.valueOf(Object).

+4

, ? HashSet, . , , , .

java-9 Set#of Map#of ( ) , . .

+5

Source: https://habr.com/ru/post/1694127/


All Articles