This example show you how to use the ListIterator
interface to iterate elements of a LinkedList
.
package org.kodejava.util;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListListIterator {
public static void main(String[] args) {
List<String> grades = new LinkedList<>();
grades.add("A");
grades.add("B");
grades.add("C");
grades.add("D");
grades.add("E");
// Retrieves object from LinkedList using the ListIterator
// interface.
ListIterator<String> iterator = grades.listIterator();
while (iterator.hasNext()) {
System.out.println("Grades: " + iterator.next());
System.out.println(" hasPrevious : " + iterator.hasPrevious());
System.out.println(" hasNext : " + iterator.hasNext());
System.out.println(" previousIndex: " + iterator.previousIndex());
System.out.println(" nextIndex : " + iterator.nextIndex());
}
}
}
The program will print the following output:
Grades: A
hasPrevious : true
hasNext : true
previousIndex: 0
nextIndex : 1
Grades: B
hasPrevious : true
hasNext : true
previousIndex: 1
nextIndex : 2
Grades: C
hasPrevious : true
hasNext : true
previousIndex: 2
nextIndex : 3
Grades: D
hasPrevious : true
hasNext : true
previousIndex: 3
nextIndex : 4
Grades: E
hasPrevious : true
hasNext : false
previousIndex: 4
nextIndex : 5
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024