According to Java documentation :
A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:
My question is, for example, suppose a while loop is runing and upon pressing 2, I call a method
public void callNextElement(int choice, LinkedList<String> linkedList) {
ListIterator<String> listIterator = linkedList.listIterator();
if (choice == 2) {
if (listIterator.hasNext()){
listIterator.next();
System.out.println("We have: " + listIterator.next());
}
}
}
Now, this would print the first element and go back to while loop to take input, now again pressing 2, I will get the first element/entry of list. And if I did :
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
....
This would print the other elements in the linked list
So my questions are :
Why doesn't it print out the 2nd element and so on in the method I called?
Why does it only works if listiterator.next() is called in a succession like I did by printing them above?
What happens if listiterator would actually store the next element position so that when even if next()
called (without succession) it would print the next element? Not the first one.
EDIT:
I feel so stupid but is it Java's garbage collection at work in my method call thing? If yes, then it makes sense why it prints 1st element each time. I'm new to Java and totally forgot about this...
Every list iterator has its own independent position in the list. Every time you call listIterator()
you get a new iterator that starts at the beginning of the list.
ListIterator<String> listIterator = linkedList.listIterator();
If you want to iterate over successive elements you need to call listIterator()
once and save the iterator somewhere so it can be reused.