Idea Analysis: To traverse a list in reverse order, first you need to obtain a ListIterator object, use the for() loop, use the hasNext() method of the ListIterator class as the judgment condition, and locate the cursor to the list by looping execution of the next() method of the ListIterator class At the end, then in another for loop, the hasPrevious() method of the ListIterator class is used as the judgment condition, and the elements in the list are output in reverse order through the previous() method of the ListIterator class.
The code is as follows:
The code copy is as follows:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();// Create a list
for (int i = 0; i < 10; i++) {// Add 10 elements to the list
list.add(i);
}
Iterator it = list.iterator();
System.out.print("The element in the ArrayList collection is: ");
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("Reverse order is:");
ListIterator<Integer> li = list.listIterator();// Get ListIterator object
for (li = list.listIterator(); li.hasNext();) {// Position the cursor to the end of the list
li.next();
}
for (; li.hasPrevious();) {// Inverse output elements in the list
System.out.print(li.previous() + " ");
}
}
}
The effect is shown in the picture: