where is the initial index of the pointer to the list should it not be the first item of the list.
does the next method
(1)returns the next element of the and points to the next element or (2) return original element and sets the pointer to the next element.
but if (1) is true then the pointer is on the first element then the first element cannot be returned i.e if (1) is true the pointer should be before the first element i.e in some kind of -1 position.
on the other hand if (2) is true then we can remove the first element but we cannot get the next element by usingthe next because we will reduce the index by 1;
which brings me to the next question does remove() method reduce the index by one or keeps it same??
The contextual code is given below::
package iterators;
import java.util.ArrayList;
import java.util.Iterator;
public class Array_practice {
public static void main(String args[])
{
ArrayList<Integer> list= new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iterator= list.iterator();
iterator.remove();//does not work why??
}
}
where is the initial index of the pointer to the list should it not be the first item of the list
No. It is before the first item of the list. You only get to the first item when you call next()
for the first time.
In fact, it's usually simpler to think of the iterator as between items. So for example, with your list:
1 2 3
^ // Initial position
^ // After calling next()
^ // After calling next()
^ // After calling next() the third time - now hasNext() will return
// false
Then remove()
- as documented - removes the item that was last returned.
You're calling remove()
before any items have been returned... so there's nothing to remove.
See more on this question at Stackoverflow