Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics incompatible types linkedlist iterators

Trying to create an iterator for a generic linked list. When I attempt to create a 'current' node for the purpose of iterating through the list based upon the head sentinel, I get an incompatible type error. Here's the relveant lines

public class LinkedList<T> implements Iterable<T>
{
    private node<T> headsent;
    private node<T> tailsent; 
    public DistanceEventList()
    {
        headsent = new node<T>();
        tailsent = new node<T>();
        headsent.setnext(tailsent);
        tailsent.setprevious(headsent);
    }
    public node<T> getheadsent()
    {
        return headsent;
    }
    ...
    public MyIterator<T> iterator() {
        return new MyIterator<T>();
    }
    public class MyIterator<T> implements Iterator<T>
    {
        private node<T> current = getheadsent();
        public T next() {
            current = current.getnext();
            return current.getdata();
        }
    private class node<T> {
        private T data;
        private node<T> next;
        private node<T> previous;    
        ...
        public node<T> getnext()
        {
            return next;
        }
    }
}

And the error produced

LinkedList.java:65: error: incompatible types
private node<T> current = getheadsent();
required: LinkedList<T#1>.node<T#2)
found: LinkedList<T#1>.node<T#1)

Seems like I've introduced two different types of T, but I'm not very experienced with generics to know for sure. Hopefully the code above is enough for someone to identify the error (it's quite gutted). Thanks!

like image 485
Matt Avatar asked Apr 25 '15 08:04

Matt


1 Answers

You have two types with the same name.

Inner classes share type variables that are declared in their outer class. So when you have

public class MyIterator<T> implements Iterator<T>
//                     ^^^

The new type declaration <T> shadows the outer one.

private node<T> current = getheadsent();
//      ^^^^^^^           ^^^^^^^^^^^
//      inner T             outer T

You can just remove the declaration:

public class MyIterator implements Iterator<T>
//                    ^^^
like image 131
Radiodef Avatar answered Oct 25 '22 05:10

Radiodef