ListIterator is a more powerful subtype of Iterator that is produced only by List classes. While Iterator can only move forward, ListIterator is bidirectional. It can produce indices of the next and previous elements relative to where the iterator is pointing in the list, and it can replace the last element it visited using the set() method. We can produce a ListIterator that points to the beginning of the List by calling listIterator() , and we can also create a ListIterator that starts out pointing to an index n in the list by calling listIterator(n).
for easier understanding I modified the code:
// collections/ListIteration.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import typeinfo.pets.*;
public class ListIteration {
public static void main(String[] args) {
List<Pet> pets = Pets.list(8);
ListIterator<Pet> it = pets.listIterator();
while (it.hasNext()) {
System.out.print(it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "; ");
}
System.out.println();
// Backwards:
while (it.hasPrevious()) {
System.out.print(it.previous().id() + " ");
}
System.out.println();
System.out.println(pets);
it = pets.listIterator(3);
System.out.println("it:" + it); // private inner class ListItr does not have size() method().
while (it.hasNext()) {
System.out.println("it.next(): " + it.next() + "it.nextIndex(): " + it.nextIndex());
// it.next(); // [1]
System.out.println("Pets.get():" + Pets.get());
it.set(Pets.get());
}
System.out.println(pets);
}
}
/* My Output:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
it:java.util.ArrayList$ListItr@66d3c617
it.next(): Mutt, it.nextIndex(): 4
Pets.get():Cymric
it.next(): Pug, it.nextIndex(): 5
Pets.get():Rat
it.next(): Cymric, it.nextIndex(): 6
Pets.get():EgyptianMau
it.next(): Pug, it.nextIndex(): 7
Pets.get():Hamster
it.next(): Manx, it.nextIndex(): 8
Pets.get():EgyptianMau
[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
*/
[1] error is:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
it.next(): Mutt
Pets.get():Cymric
it.next(): Cymric
Pets.get():EgyptianMau
it.next(): Manx
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:862)
at ListIteration.main(ListIteration.java:26)
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/collections/ListIteration.java
4. https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--