Can anyone explain why I am getting this error?
Here is a stack class I implemented using a doubly linked list:
import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>{
private Node first;
private int N;
private class Node{
private Node next;
private Node prev;
private Item item;
}
public Iterator<Item> iterator(){
return new ReverseIterator<Item>();
}
private class ReverseIterator<Item> implements Iterator<Item>{
private Node x;
private ReverseIterator(){
if (first != null)
x = first.prev;
}
public boolean hasNext(){
return x != null;
}
public Item next(){
Item i = x.item;
x = x.prev;
return i;
}
public void remove(){
}
}
public void push(Item i){
if (isEmpty()){
first = new Node();
first.item = i;
first.next = first;
first.prev = first;
}
else{
Node x = new Node();
x.item = i;
x.next = first;
x.prev = first.prev;
first.prev.next = x;
first.prev = x;
}
N++;
}
public Item pop(){
assert !isEmpty() : "Stack is empty";
Item i = first.prev.item;
if (N == 1)
first = null;
else{
first.prev.prev.next = first;
first.prev = first.prev.prev;
}
N--;
return i;
}
public boolean isEmpty(){
return N == 0;
}
public int size(){
return N;
}
public static void main(String[] args){
}
}
The compiler says there’s an error in Item i = x.item;, expected Item, found Item. The solution was to replace ReverseIterator<Item> with ReverseIterator. Can someone explain why I got the error I did by adding <Item>?
Thanks
Just because you used the same name for the type variable (
Item) does not mean that it represents the same generic type.If you declare a nested class
N<T>, inside a generic classC<T>, theTfromC<T>is effectively hidden from the body ofN<T>. It is exactly the same principle as declaring a class level field calledxand declaring a method parameter in that class, also calledx. Your innermost declaring scope hides anything from the outside.If
ReverseIteratorwere a static nested class, you would be obliged to add the<Item>to its declaration, because instances of it would not have an enclosing instance ofStack<Item>. And the same error would result, even though in this case there would be no hiding going on. In fact, you would need to add the type variable toNodeas well.