加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java HashSet中元素的排序

发布时间:2020-12-15 07:37:17 所属栏目:Java 来源:网络整理
导读:为什么第二组和第三组保留顺序: Integer[] j = new Integer[]{3,4,5,6,7,8,9};LinkedHashSetInteger i = new LinkedHashSetInteger();Collections.addAll(i,j);System.out.println(i); HashSetInteger hi = new HashSetInteger(i);System.out.println(hi);
为什么第二组和第三组保留顺序:

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,9
3,9

解决方法

第二个(只使用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.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读