Java 集合 以反向顺序迭代LinkedList

使用 LinkedList 类的 descendingIterator()方法以相反的顺序迭代链表的程序。

程序

import java.util.LinkedList;
import java.util.Iterator;
class LinkedListDemo {

  public static void main(String[] args) {

     // create a LinkedList
     LinkedList<String> list = new LinkedList<String>();

     // Adding elements to the LinkedList
     list.add("Element1");
     list.add("Element2");
     list.add("Element3");
     list.add("Element4");

     // Displaying LinkedList elements
     System.out.println("LinkedList elements: "+list);

     /* public Iterator<E> descendingIterator(): Returns an 
      * iterator over the elements in this list in reverse 
      * sequential order. The elements will be returned in 
      * order from last (tail) to first (head).
      */
     Iterator it = list.descendingIterator();

     // Displaying list in reverse order
     System.out.println("Elements in Reverse Order:");
     while (it.hasNext()) {
        System.out.println(it.next());
     }
  }
}

输出:

LinkedList elements: [Element1, Element2, Element3, Element4]
Elements in Reverse Order:
Element4
Element3
Element2
Element1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程