im having problems java generics. when use next() iterator doesn't return object of same type instantiated with. recieve incompatible types error. can help?
i recieve xlint warning when compile linked list class.
public class linkedlist<type> { private node<type> sentinel = new node<type>(); private node<type> current; private int modcount; public linkedlist() { // initialise instance variables sentinel.setnext(sentinel); sentinel.setprev(sentinel); modcount = 0; } public void prepend(type newdata) { node<type> newn = new node<type>(newdata); node<type> temp; temp = sentinel.getprev(); sentinel.setprev(newn); temp.setnext(newn); newn.setprev(temp); newn.setnext(sentinel); modcount++; } private class listiterator implements iterator { private int curpos, expectedcount; private node<type> itnode; private listiterator() { curpos =0; expectedcount = modcount; itnode = sentinel; } public boolean hasnext() { return (curpos < expectedcount); } public type next() { if (modcount != expectedcount) throw new concurrentmodificationexception("cannot mutate in context of iterator"); if (!hasnext()) throw new nosuchelementexception("there no more elements"); itnode = itnode.getnext(); curpos++; current = itnode; return (itnode.getdata()); } } } here error occurs in main class after list created , filled different types of shapes.
shape test; iterator iter = unsorted.iterator(); test = iter.next();
iterator generic interface, listiterator neither generic nor parameterizes iterator. start making listiterator implement iterator<type>:
private class listiterator implements iterator<type> { // rest should fine } or making listiterator generic (more complicated):
private class listiterator<t> implements iterator<t> { private int curpos, expectedcount; private node<t> itnode; private listiterator() { curpos = 0; expectedcount = modcount; itnode = sentinel; } public boolean hasnext() { return (curpos < expectedcount); } public t next() { // snip } }
Comments
Post a Comment