Java USES listIterator to share the arraylist example in reverse order

  • 2020-04-01 03:03:28
  • OfStack

Thought analysis: To iterate through a list in reverse order, first get a ListIterator object, use the for() loop, take the hasNext() method of ListIterator class as the judgment condition, execute the next() method of ListIterator class through the loop to locate the cursor to the end of the list, then in another for loop, take the hasPrevious() method of ListIterator class as the judgment condition, The elements in the list are output in reverse order through the previous() method of the ListIterator class.

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 of
            for (int i = 0; i < 10; i++) {//Add 10 elements to the list
                list.add(i);
            }
            Iterator it = list.iterator();
            System.out.print("ArrayList The elements in the set are: ");
            while(it.hasNext()){
                System.out.print(it.next()+" ");
            }      
            System.out.println();
            System.out.println(" After the reverse order: ");
            ListIterator<Integer> li = list.listIterator();//Gets the ListIterator object
            for (li = list.listIterator(); li.hasNext();) {//Position the cursor to the end of the list
                li.next();
            }
            for (; li.hasPrevious();) {//The reverse outputs the elements in the list
                System.out.print(li.previous() + " ");
            }
        }
}

The effect is as follows:

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201402/20140227154246.jpg? 201412715433 ">


Related articles: