当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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<Integer, String> 
            LinkedList<String> list = new LinkedList<String>(); 
  
            // 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<Integer, String> 
            LinkedList<Integer> 
                list = new LinkedList<Integer>(); 
  
            // 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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 LinkedList descendingIterator() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。