For the list,
Train of Thought Analysis: to traverse a list in reverse order, first obtain a ListIterator, use the for () hasNext () method as the judgment condition, and execute next () cyclically () the method locates the cursor at the end of the list, and then uses another hasPrevious () method as the judgment condition to output the elements in the list in reverse order using the previous () method.
The Code 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. add (I);} Iterator it = list. iterator (); System. out. print ("the element in the ArrayList set is:"); while (it. hasNext () {System. out. print (it. next () + "");} System. out. println (); System. out. println ("Backward:"); ListIterator <Integer> li = list. listIterator (); // obtain the ListIterator object for (li = list. listIterator (); li. hasNext ();) {// locate the cursor to the end of the list li. next () ;}for (; li. hasPrevious ();) {// The System element in the output list in reverse order. out. print (li. previous () + "");}}}
Effect