java - Why can't we return an ArrayList.iterator() for Iterator? -
java - Why can't we return an ArrayList<Foo>.iterator() for Iterator<IFoo>? -
i have method returns iterator<ifoo>
. within method, if seek homecoming somearraylist
of type arraylist<foo>
, compilation error saying: type mismatch: cannot convert iterator<foo> iterator<ifoo>
here's type hierarchy:
interface:ifoo --class: foo (implements ifoo)
and, here's method:
public iterator<ifoo> iterator() { homecoming somearraylist.iterator(); }
my question is, when method wants me homecoming of type iterator<ifoo>
, why can't homecoming somearraylist
of type arraylist<foo>
since foo implements ifoo
?
the method in question public iterator<ifoo> iterator()
cannot modified since i'm implementing interface.
i should have mentioned before. sorry.
going off recent edit, can't modify method signature (which bad, because more flexible signature have avoided this...):
one solution create new list
proper type , utilize iterator that. works because various constructors lists far more flexible in types take , take subtypes. main disadvantage produce shallow re-create of original arraylist
, takes space (albeit not much unless you're working big lists). posted reply in much more compact form.
public iterator<ifoo> iterator() { homecoming new arraylist<ifoo>(somearraylist).iterator(); }
you have specify type arguments explicitly here because otherwise type inferred foo
, leaves were.
alternatively, if space required new arraylist()
phone call isn't appealing, can write anonymous subclass of iterator
acts wrapper (i think got syntax right; might have made minor error or two, should easy fix). it's more writing, it's leaner on memory usage, might desirable:
public iterator<ifoo> iterator() { homecoming new iterator<ifoo>() { private final iterator<? extends ifoo> iterator = somearraylist.iterator(); @override public boolean hasnext() { homecoming iterator.hasnext(); } @override public number next() { homecoming iterator.next(); } @override public void remove() { iterator.remove(); } }; }
one of import thing note these solutions not equivalent.
your solution , first solution homecoming iterators operate on different list original one. distinct list shallow copy, you'll same results hasnext()
, next()
. however, if phone call remove()
, original list remain unaffected, , re-create changed.
the anonymous subclass perform operations on original list, if original solution had worked in first place.
java iterator
Comments
Post a Comment