Java – order and difference between HashSet and JDK 7 / 8

This is a two-part question:

>Whether HashSet implements some hidden sorting mechanisms, or just references documents: it cannot guarantee the iterative order of the set; In particular, it does not guarantee that orders will remain unchanged over time Tell me that sometimes orders may change in the future and / or depending on memory usage? > When I switch between jdks, why do I 'order' completely different (I dare say)?

for instance:

for (int i = 0; i < 1000; i++) {
        Set<String> stringSet = new HashSet<>();
        stringSet.add("qwe");
        stringSet.add("rtz");
        stringSet.add("123");
        stringSet.add("qwea");
        stringSet.add("12334rasefasd");
        stringSet.add("asdxasd");
        stringSet.add("arfskt6734");
        stringSet.add("123121");
        stringSet.add("");
        stringSet.add("qwr");
        stringSet.add("rtzz");
        stringSet.add("1234");
        stringSet.add("qwes");
        stringSet.add("1234rasefasd");
        stringSet.add("asdxasdq");
        stringSet.add("arfskt6743");
        stringSet.add("123121 ");
        stringSet.add(" ");
        System.out.println(stringSet);
    }

No matter how many times I run, the following output will be generated:

JDK 7:[,123,qwea,asdxasdq,qwe,qwr,123121,arfskt6743,1234rasefasd,qwes,rtz,rtzz,1234,12334rasefasd,asdxasd,arfskt6734,123121]

JDK 8:[,asdxasd]

Obviously, an empty string and only a blank string are two boot modes, but the rest are completely different

Solution

Update the changes page according to the collection

So, basically

The algorithm used for hash sets has been changed to improve performance It becomes a balanced tree instead of a linked list

This change may change the iterative order of your collection and has determined that you should fix this behavior if you rely on it

You see a better collection implementation. It may look orderly, but it's pure coincidence

I suggest that you do not rely on the iterative order of the set, because the order is not guaranteed

@Edit

As mentioned by user Holger, another concept is also important,

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>