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

6th Aug 2019, 2:22 AM
salar vahidi
salar vahidi - avatar
2 Respostas
+ 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();
6th Aug 2019, 5:50 PM
Andy Wong
Andy Wong - avatar
0
Iterator returns object
25th Aug 2020, 2:15 PM
Rohit Rathore
Rohit Rathore - avatar