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!
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>
// ^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With