Search code examples
javadeque

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


I got an error of incompatible type: cannot infer type-variable(s) E (actual and formal argument lists differ in length) from the 2nd statement of the following code,

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

However, substitute LinkedList with ArrayDeque fixes the error,

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

Both LinkedList and ArrayDeque implement the Deque interface. I am confused why it works for ArrayDeque but not for LinkedList?


Solution

  • The difference is in their constructors that you pass:

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

    After expanding you get:

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

    Where LinkedList does not have constructor taking int index.
    To fix your issue just write (the index is index in your array):

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