gpt4 book ai didi

java - Java HashSet 中元素的排序

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:57 25 4
gpt4 key购买 nike

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

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 :

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.)

关于java - Java HashSet 中元素的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9345651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com