Java Generics incompatible types linkedlist iterators -
trying create iterator generic linked list. when attempt create 'current' node purpose of iterating through list based upon head sentinel, incompatible type error. here's 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 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 i've introduced 2 different types of t, i'm not experienced generics know sure. code above enough identify error (it's quite gutted). thanks!
you have 2 types same name.
inner classes share type variables declared in outer class. when have
public class myiterator<t> implements iterator<t> // ^^^
the new type declaration <t>
shadows outer one.
private node<t> current = getheadsent(); // ^^^^^^^ ^^^^^^^^^^^ // inner t outer t
you can remove declaration:
public class myiterator implements iterator<t> // ^^^
Comments
Post a Comment