Search code examples
javagenericsincompatibletypeerror

Inner class generics - Incompatible types


i just can't seem to get why i get that these are incompatible types, is it just bc they are on different class levels? I just can't quite get why.

public class PrependLinearListImpl<T>{
    private Node<T> first;

    private class Node<T> {
        private T head;
        private Node<T> tail;
        Node(T head) {
            this.head = head;
            this.tail = first;
            first = this;
        }
    }

}

Solution

  • It's because PrependLinearListImpl<T>.Node already inherits the generic argument from its outer class. It's not necessary to redefine the generic component.

    The following should work as-is:

    public class PrependLinearListImpl<T>{
        private Node first;
    
        private class Node {
            private T head;
            private Node tail;
            Node(T head) {
                this.head = head;
                this.tail = first;
                first = this;
            }
        }
    
    }
    

    If Node were static, then it would be necessary to provide its own generic parameter.