I have the following design:
I have an Abstract class Instance,
I have a class Library that extends Instance and
I have a class File that also extends Instance
I’ve created my own linked list implementation and it’s defined as follows:
public class List<T extends Instance> implements Iterable {
//some other code here
public Iterator iterator(){
return new ListIterator(this);
}
now I’ve created a class
public class ListIterator<T extends Instance> implements Iterator<T> {
private List thisList;
private Node current;
public ListIterator(List l){
thisList=l;
current=thisList.head.next;
}
@Override
public boolean hasNext() {
if(current==null)
return false;
return false;
}
@Override
public T next() {
Node temp=current;
current=current.next;
return temp.data;
}
}
Where Node is
public class Node<T extends Instance> {
public Node<T> next;
public Node<T> prev;
public T data;
public Node(T data,Node prev, Node next){
this.data=data;
this.prev=prev;
this.next=next;
}
}
so my problem is as follows: the line return temp.data rises an error:
Type mismatch – cannot convert from Instance to T.
What is wrong with this code?
I’d say that
Node.datais a reference to anInstanceobject? If that is the case, the compiler can’t automatically change anInstanceto aT, because even thoughTis anInstanceobject (T extends Instance), any givenInstancemight not be aT.The Java Generics tutorial explains it: http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html
Also, in your
List<T>class, you should be specifyingIteratorandListIteratoras generic usingIterator<T>andListIterator<T>, or else the compiler won’t be able to handle the generics properly. YourNodereference also needs to be generic:Node<T>Hence you should be using
and
The compiler will usually warn you when you’re using a raw type for a generic class.