有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java哈希集中元素的集合排序

为什么第二组和第三组保持顺序:

Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet<Integer> i = new LinkedHashSet<Integer>();
Collections.addAll(i,j);
System.out.println(i); 

HashSet<Integer> hi = new HashSet<Integer>(i);
System.out.println(hi); 

LinkedHashSet<Integer> o = new LinkedHashSet<Integer>(hi);
System.out.println(o); 

以下是我得到的输出:

3,4,5,6,7,8,9
3,4,5,6,7,8,9
3,4,5,6,7,8,9

共 (2) 个答案

  1. # 1 楼答案

    第二个(仅使用HashSet)只是巧合。从JavaDocs开始:

    This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

    第三个(LinkedHashSet)是designed是这样的:

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

  2. # 2 楼答案

    @Behrang的答案是好的,但更具体地说,HashSet似乎与LinkedHashSet顺序相同的唯一原因是integer.hashCode()恰好是整数值本身,所以在HashSet内部存储器中,数字恰好是顺序的。这是高度特定于实现的,正如@Behrang所说,这真是巧合

    例如,如果使用new HashSet<>(4)将桶的初始数量设置为4(而不是16),则可能会得到以下输出:

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

    如果你坚持价值观>;=16.你可能会得到这样的结果:

    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]