Java HashSet 中元素的排序 [英] Ordering of elements in Java HashSet
问题描述
为什么第二组和第三组保持顺序:
Why do the second and third sets preserve order:
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
推荐答案
第二个(仅使用 HashSet
)只是一个巧合.来自 JavaDocs:
The second one (just using HashSet
) is only a coincidence. From the JavaDocs:
这个类实现了 Set 接口,由一个哈希表(实际上是一个 HashMap 实例)支持.它不保证集合的迭代顺序;特别是,它不保证订单会随着时间的推移保持不变.此类允许空元素.
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
) 是 设计就是这样:
The third one (LinkedHashSet
) is designed to be like that:
Set 接口的哈希表和链表实现,具有可预测的迭代顺序.此实现与 HashSet 的不同之处在于它维护一个双向链表,贯穿其所有条目.这个链表定义了迭代顺序,也就是元素被插入到集合中的顺序(插入顺序).请注意,如果将元素重新插入到集合中,则插入顺序不会受到影响.(如果在调用 s.contains(e) 之前立即返回 true 时调用了 s.add(e),则元素 e 将重新插入到集合 s 中.)
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.)
这篇关于Java HashSet 中元素的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!