Reputation: 949
I've got an outer class DoublyLinkedList<T>
and two inner classes DoublyLinkedNode<T>
as well as DoublyLinkedListIterator<T>
. They are arranged as follows:
public class DoublyLinkedList<T> extends Collection<T> {
private DoublyLinkedNode<T> head;
private DoublyLinkedNode<T> tail;
public class DoublyLinkedNode<T> {
private DoublyLinkedNode<T> prev;
private DoublyLinkedNode<T> next;
T element;
}
public class DoublyLinkedListIterator<T> implements ListIterator<T> {
private DoublyLinkedNode<T> current = head;
}
}
Now since I heard / read on multiple pages in stackoverflow and other sources that an Iterator should be implemented in the corresponding iterable class like DoublyLinkedList<T>
, I thought it would be easier since you have access to the outer classes fields. Now I want to initialize an instance of DoublyLinkedListIterator<T>
, but Eclipse says at this point:
private DoublyLinkedNode<T> current = head;
inside the DoublyLinkedListIterator<T>
that:
Type mismatch: cannot convert from DoublyLinkedList.DoublyLinkedNode< T > to DoublyLinkedList.DoublyLinkedNode< T >
And the only way to resolve this is by casting it with the same type again:
private DoublyLinkedNode<T> current = (DoublyLinkedNode<T>) head;
Why is that so?
Upvotes: 3
Views: 1335
Reputation: 178363
You've declared inner classes DoublyLinkedNode
and DoublyLinkdListIterator
.
Inner classes have in scope all generic type parameters of the enclosing class, so T
is already available to them. When you declare them again, you are hiding the T
on the enclosing class. They are different T
s.
Remove the re-declarations of T
that are hiding the outer T
(and your class should implement Collection
, which is an interface), and let your inner classes use the outer T
:
public class DoublyLinkedList<T> implements Collection<T> {
private DoublyLinkedNode head;
private DoublyLinkedNode tail;
public class DoublyLinkedNode {
private DoublyLinkedNode prev;
private DoublyLinkedNode next;
T element;
}
public class DoublyLinkedListIterator implements ListIterator<T> {
private DoublyLinkedNode current = head;
}
}
Upvotes: 11