0
what object does iterator() return?
I wonder what object reference iterator() returns in a code like this: LinkedList<Integer> a = new LinkedList<Integer>(); a.add(1); a.add(2); a.add(3); Iterator<Integer> itr = a.iterator(); //which object is this? I was looking for the overriden version of iterator() in JavaDoc to see what object it returns and throught it, I finally found an inner class named "ListItr" as the object which is returned to caller(a.iterator()). but if that is the object which is eventually being returned and assigned to itr(the reference), why can't I use its other methods? only methods inside Iterator interface are available I'm a bit confused. I'd appreciate any thorough and clear explanation
2 Réponses
+ 1
Since called List#iterator only gives you the super class of ListIterator<E> - which is the Iterator interface, you can only use methods from the Iterator interface. In order to use the methods from the child class (ListIterator), you must perform a down cast to get the more specific object.
Hence it would be this:
LinkedList<Integer> a = new LinkedList<Integer>();
a.add(1);
a.add(2);
a.add(3);
Iterator<Integer> itr = a.iterator(); //which object is this?
ListIterator<Integer> listIterator = (ListIterator<Integer>) itr;
alternatively you can just call List#listIterator();
0
Iterator returns object