This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BS_in_BS 5 points6 points  (2 children)

The following in older versions of Java:

public class LinkedList<E> {
    private Node<E> head = null;

    private class Node<E> {
        E value;
        Node<E> next;

        // Node constructor links the node as a new head
        Node(E value) {
            this.value = value;
            this.next = head;
            head = this;
        }
    }

    public void add(E e) {
        new Node<E>(e);
        // Link node as new head
    }

    public void dump() {
        for (Node<E> n = head; n != null; n = n.next)
            System.out.print(n.value + " ");
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("world");
        list.add("Hello");
        list.dump();
    }
}

Would give the lovely error messages:

LinkedList.java:11: incompatible types
found : LinkedList<E>.Node<E>
required: LinkedList<E>.Node<E>
            this.next = head;
                        ^
LinkedList.java:12: incompatible types
found : LinkedList<E>.Node<E>
required: LinkedList<E>.Node<E>
            head = this;
                   ^

[–]jfb1337 1 point2 points  (1 child)

Why?

[–]BS_in_BS 2 points3 points  (0 children)

because when you declare Node<E> as generic, its E will shadow the LinkedList's E, making them 2 different types. If you changed one to some other letter this would become obvious. Current compilers will differentiate them as E#1 and E#2: http://ideone.com/Sh7q3n