繁体   English   中英

为什么我不能使用LinkedList :: new?

[英]Why can't I use LinkedList::new?

假设我有一个HashMap作为Map<Integer, List<Integer>> map = new HashMap<>();

Now List<Integer> values = computeIfAbsent(key, ArrayList::new); 完美的工作,但List<Integer> values = computeIfAbsent(key, LinkedList::new); 抛出编译错误。

我可以在ArrayList和LinkedList中看到no-arg构造函数。 我在这里缺少什么,有人可以解释这种行为吗?

您可能打算做的是将lamba表达式指定为初始化:

List<Integer> values = map.computeIfAbsent(key, a -> new ArrayList<>());

要么

List<Integer> values = map.computeIfAbsent(key, a -> new LinkedList<>());

原因,为什么代码

List<Integer> values = computeIfAbsent(key, LinkedList::new);

不会编译的是,使用单个参数最接近当前语法的构造函数需要Collection<? extends E> c Collection<? extends E> c而不是Integer ,因此无法解析。

另一方面,之所以如此

List<Integer> values = map.computeIfAbsent(key, ArrayList::new);

compiles是,它有一个构造函数接受int参数但请注意它的列表容量。

所需的lambda必须是签名Function<? super K,? extends V> mappingFunction Function<? super K,? extends V> mappingFunction Function<? super K,? extends V> mappingFunction ,所以当你写:

List<Integer> values = map.computeIfAbsent(key, ArrayList::new);

必须给出一个构造函数,其参数类型与keyInteger )的类型兼容。 ArrayList有一个但LinkedList没有:

ArrayList构造函数:

数组列表()

ArrayList(集合c)

ArrayList(int initialCapacity)

LinkedList构造函数:

链表()

LinkedList(Collection c)

很遗憾它适用于ArrayList的事实可能不是一个好点,因为它构造了一个具有初始容量的空ArrayList (这可能会导致奇怪的边框效应)。

您可以参考Java中的方法参考

使用以下命令

List<Integer> values = map.computeIfAbsent(key, x -> new ArrayList<>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM