Ordering of elements in Java HashSet

后端 未结 2 799
迷失自我
迷失自我 2020-11-29 13:13

Why do the second and third sets preserve order:

Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet i = new LinkedHashSet

        
2条回答
  •  时光取名叫无心
    2020-11-29 13:59

    @Behrang's answer is good but to be more specific, the only reason why the HashSet seems to be in the same order as the LinkedHashSet is that integer.hashCode() happens to be the integer value itself so the numbers happen to be in order in the HashSet internal storage. This is highly implementation specific and as @Behrang says, really a coincidence.

    For example, if you use new HashSet<>(4) which sets the initial number of buckets to be 4 (instead of 16) then you might have gotten the following output:

    HashSet hi = new HashSet(4);
    ...
    [3, 4, 5, 6, 7, 8, 9]
    [8, 9, 3, 4, 5, 6, 7]
    [8, 9, 3, 4, 5, 6, 7]
    

    If you had stuck in values >= 16, you might get something like this:

    Integer[] j = new Integer[] { 3, 4, 5, 6, 7, 8, 9, 16 };
    ...
    [3, 4, 5, 6, 7, 8, 9, 16]
    [16, 3, 4, 5, 6, 7, 8, 9]
    [16, 3, 4, 5, 6, 7, 8, 9]
    

提交回复
热议问题