Search code examples
javatypescastingmismatch

Type mismatch error when assigning a variable to an object of the same type


I'm working on an Iterator for a linked list class. I am assigning nodes to variables within an inner class and am getting a "Type mismatch" error. Relevant code is below.

public class RegLinkList<T> implements Iterable<T>{
    private Node<T> head;
public RegLinkList() {
        head = null;
    }   
 public class Node<T> {
   public Node<T> next = null;
   public T data = null;

   Node(T data){
        this.data = data;
    }
  }
    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = head;
    Node<T> previous = head;

I get this:

    Type mismatch: cannot convert from 
    RegLinkList<T>.Node<T> to RegLinkList<T>.Node<T>    

Edit: My current solution is an unchecked cast of

    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = (Node<T>) head;
    Node<T> previous = (Node<T>) head;

Solution

  • The reason why you get this error is that the compiler does what you say and not what you mean. The T for ListIterator and the T of the RegLinkList are seen as two different types. It would become more clear if you used e.g. U instead of T.

    A solution to your problem could be making the classes static and pass the head element to the constructor. That way you still declare different Ts but because you pass the original element (and therefor "telling" the compiler that the one T is the same as the other), it will be happy. The following code is happily compiled (I added missing method implementations with no functionalities):

    import java.util.Iterator;
    
    public class RegLinkList<T> implements Iterable<T> {
        private Node<T> head;
    
        public RegLinkList() {
            head = null;
        }
    
        public static class Node<T> {
            public Node<T> next = null;
            public T data = null;
    
            Node(T data) {
                this.data = data;
            }
        }
    
        public static class ListIterator<T> implements Iterator<T> {
            Node<T> current;
            Node<T> previous;
    
            public ListIterator(Node<T> head) {
                current = head;
                previous = head;
            }
    
    
            @Override
            public boolean hasNext() {
                return false;
            }
            @Override
            public T next() {
                return null;
            }
        }
    
        @Override
        public Iterator<T> iterator() {
            return new ListIterator<T>(head);
        }
    }