"incompatible types: cannot infer type-variable" 对于链表

"incompatible types: cannot infer type-variable" for LinkedList

我从以下代码的第 2 条语句中得到 incompatible type: cannot infer type-variable(s) E (actual and formal argument lists differ in length) 错误,

Deque<TreeNode>[] stacks = new Deque[2];
Arrays.set(stacks, LinkedList::new);

但是,将 LinkedList 替换为 ArrayDeque 可以修复错误,

Arrays.set(stacks, ArrayDeque::new);

LinkedListArrayDeque都实现了Deque接口。我很困惑为什么它适用于 ArrayDeque 但不适用于 LinkedList?

不同之处在于您传递的构造函数:

public LinkedList(Collection<? extends E> c);
public LinkedList();
public ArrayDeque(int numElements);

展开后得到:

Arrays.setAll(stacks, index -> new LinkedList<TreeNode>(index));
Arrays.setAll(stacks, index -> new ArrayDeque<>(index));

其中 LinkedList 没有采用 int index 的构造函数。
要解决您的问题,只需编写(index 是数组中的索引):

Arrays.setAll(stacks, index -> new LinkedList<TreeNode>());