gpt4 book ai didi

java - Collectors.toSet() 是否总是返回 HashSet ?什么是契约(Contract)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:30:18 24 4
gpt4 key购买 nike

Javadoc 说

Returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned; if more control over the returned Set is required, use toCollection(java.util.function.Supplier).

所以 Collectors.toCollection(HashSet::new) 似乎是避免这里出现问题的好主意 (SO question)。

我的问题是,尽我所能,除了 HashSet

之外,我无法从 toSet() 返回任何其他内容

这是我使用的代码:

public static void main(String[] args) {
List<Integer> l = Arrays.asList(1,2,3);

for (int i = 0 ; i++<1_000_000;){
Class clazz = l.stream().collect(Collectors.toSet()).getClass();

if (!clazz.equals(HashSet.class)) {
System.out.println("Not a HashSet");
}
}
}

那么,为什么 Javadoc 声明不能保证实际上存在......

最佳答案

JavaDoc 声明没有保证,但这并不妨碍任何特定实现总是返回特定类型的集合。这只是设计师说他们不想限制 future 的实现可以做什么。它没有说明当前实现的实际作用。

换句话说,您已经发现了实现定义的行为(总是返回一个HashSet),但是如果您指望它,您将来可能会遇到问题。

关于java - Collectors.toSet() 是否总是返回 HashSet ?什么是契约(Contract)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37055794/

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