gpt4 book ai didi

java - LinkedHashSet 构造函数是否保留顺序

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:04 24 4
gpt4 key购买 nike

构造函数LinkedHashSet(Collection<? extends E> c)假设参数是有序集合,保证其参数的保留顺序?我们如何确定这一点?

Javadoc 文档没有说明顺序:

Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75).

我看不出有任何理由不保留顺序,但我想知道它是否有保证(对于当前和 future 的实现)。

最佳答案

查看 java.util.LinkedHashSet 的 Java 8 实现,您有这个构造函数:

public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}

那么addAll的内容是什么?

public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}

addAll 使用循环遍历构造函数中使用的集合:

for (E e : c)

这意味着如果构造函数中使用的集合实现是有序的(例如 java.util.TreeSet),那么新的 LinkedHashSet 实例的内容也将是订购。

Java 9 中的实现非常相似。

是的,订单会被保留,以防传入的集合被订购。

您只能通过检查此特定情况下的实现来确定这一点。

关于java - LinkedHashSet 构造函数是否保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46830838/

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