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 :
这个类实现了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
) 设计为:
Set接口的哈希表和链表实现,具有可预测的迭代顺序。此实现不同于HashSet,因为它维护一个贯穿其所有条目的双向链表。此链接列表定义迭代排序,它是将元素插入集合(插入顺序)的顺序。请注意,如果元素重新插入到集合中,则插入顺序不会受到影响。 (如果s.contains(e)在调用之前立即返回true,则调用s.add(e)时,元素e被重新插入到集合中。)
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屋!