Java Reference
In-Depth Information
head = this;
^
It appears that the compiler is complaining that a type isn't compatible with itself! Appearances, as
usual, are deceiving. The "found" and "required" types are unrelated to each other. They appear
identical because the program uses the same name to refer to different types. Specifically, the
program contains two different declarations for type parameters named E . The first is the type
parameter for LinkedList , and the second is the type parameter for the inner class
LinkedList.Node . The latter shadows the former within the inner class. The lesson that we learned
in Puzzles 71 , 73 , and 79 applies here as well: Avoid shadowing type parameter names.
There is no way to refer to a type parameter except by its simple name, so the error message has no
way to tell you that these two uses of the name E refer to different types. The error message would
be clearer if we systematically renamed the type parameter for Node from E to, say, T . It wouldn't fix
the problem, but it would shed some light on it. This approach yields the following error messages:
LinkedList.java:11: inco>mpatible types
found : LinkedList<E>.Node<E>
required: LinkedList<E>.Node<T>
this.next = head;
^
LinkedList.java:12: incompatible types
found : LinkedList<E>.Node<T>
required: LinkedList<E>.Node<E>
head = this;
^
What the compiler is trying to tell us is that the program is way too complicated. An inner class of
a generic class has access to the type parameters of its outer class. It was the clear intent of the
program's author that the type parameter for a Node would always be the same as for the enclosing
LinkedList , so there is no reason for Node to have a type parameter of its own. To fix the program,
simply eliminate the type parameter in the inner class:
 
 
Search WWH ::




Custom Search