📜  Java中的 LinkedList descendingIterator() 方法及示例

📅  最后修改于: 2022-05-13 01:55:24.909000             🧑  作者: Mango

Java中的 LinkedList descendingIterator() 方法及示例

Java.util.LinkedList类的descendingIterator()方法用于以相反的顺序返回此LinkedList 中元素的迭代器。元素将按从最后(尾)到第一个(头)的顺序返回。

句法:

public Iterator descendingIterator()

返回值:此方法以相反的顺序返回此 LinkedList 中元素的迭代器

以下是说明descendingIterator()方法的示例

示例 1:

// Java program to demonstrate
// descendingIterator() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of TreeMap
            LinkedList list = new LinkedList();
  
            // add some elements to list
            list.add("A");
            list.add("B");
            list.add("C");
  
            // print the linked list
            System.out.println("LinkedList:" + list);
  
            // set Iterator as descending
            // using descendingIterator() method
            Iterator x = list.descendingIterator();
  
            // print list with descending order
            while (x.hasNext()) {
                System.out.println("Value is : "
                                   + x.next());
            }
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : "
                               + e);
        }
    }
}
输出:
LinkedList:[A, B, C]
Value is : C
Value is : B
Value is : A

示例 2:

// Java program to demonstrate
// descendingIterator() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of TreeMap
            LinkedList
                list = new LinkedList();
  
            // add some elements to list
            list.add(10);
            list.add(20);
            list.add(30);
  
            // print the linked list
            System.out.println("LinkedList:" + list);
  
            // set Iterator as descending
            // using descendingIterator() method
            Iterator x = list.descendingIterator();
  
            // print list with descending order
            while (x.hasNext()) {
                System.out.println("Value is : "
                                   + x.next());
            }
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
LinkedList:[10, 20, 30]
Value is : 30
Value is : 20
Value is : 10