Collectors.toSet()是否总是返回HashSet吗?什么合同 [英] Does Collectors.toSet() always return a HashSet ? What is the contract?
问题描述
Javadoc说
返回一个收集器,该收集器将输入元素累积到一个新的放.对于类型,可变性,可序列化性,或返回的Set的线程安全性;如果更多地控制返回的Set是必需的,使用toCollection(java.util.function.Supplier).
因此, 那么,为什么Javadoc声明实际上并不能保证... JavaDoc声明没有保证,但是这并不妨碍任何特定的实现总是返回特定类型的set.设计师只是在说他们不想限制将来的实现可以做什么.它并没有说明当前实现的实际作用. 换句话说,您发现了定义的实现行为(总是返回 Javadoc says 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). So My problem is, as hard as I've tried, I can not get anything else returned from Here is the code I used : Why then, does the Javadoc state that there is no guarantee when in fact, there is... The JavaDoc states there is no guarantee, but that doesn't prevent any specific implementation from always returning a specific type of set. This is just the designers saying they don't want to limit what a future implementation can do. It says nothing about what the current implementation actually does. In other words, you have discovered implementation defined behavior (always return a 这篇关于Collectors.toSet()是否总是返回HashSet吗?什么合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Collectors.toCollection(HashSet :: new)
似乎是避免此处出现问题的好主意( HashSet
),但是如果您指望将来可能会遇到问题.>
Collectors.toCollection(HashSet::new)
seems like a good idea to avoid problems here (SO question).toSet()
than a HashSet
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");
}
}
}
HashSet
), but if you count on that you may have problems in the future.