當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack listIterator()用法及代碼示例


Java.util.Stack類的listIterator()方法用於返回此堆棧中的元素的列表迭代器(按適當順序)。返回的列表迭代器為fail-fast。

用法:

public ListIterator listIterator()

返回值:此方法返回此堆棧中元素的列表迭代器(按適當順序)。


以下示例說明了listIterator()方法。

示例1:

// Java program to demonstrate 
// listIterator() method 
// for String value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // Creating object of Stack<Integer> 
            Stack<String> 
                stack = new Stack<String>(); 
  
            // adding element to stack 
            stack.add("A"); 
            stack.add("B"); 
            stack.add("C"); 
            stack.add("D"); 
  
            // print stack 
            System.out.println("Stack: "
                               + stack); 
  
            // Creating object of ListIterator<String> 
            // using listIterator() method 
            ListIterator<String> 
                iterator = stack.listIterator(); 
  
            // Printing the iterated value 
            System.out.println("\nUsing ListIterator:\n"); 
            while (iterator.hasNext()) { 
                System.out.println("Value is : "
                                   + iterator.next()); 
            } 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Stack: [A, B, C, D]

Using ListIterator:

Value is : A
Value is : B
Value is : C
Value is : D

示例2:

// Java code to illustrate lastIndexOf() 
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
  
        // Creating an empty Stack 
        Stack<Integer> stack = new Stack<Integer>(); 
  
        // Use add() method to add elements in the Stack 
        stack.add(1); 
        stack.add(2); 
        stack.add(3); 
        stack.add(10); 
        stack.add(20); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Creating object of ListIterator<String> 
        // using listIterator() method 
        ListIterator<Integer> 
            iterator = stack.listIterator(); 
  
        // Printing the iterated value 
        System.out.println("\nUsing ListIterator:\n"); 
        while (iterator.hasNext()) { 
            System.out.println("Value is : "
                               + iterator.next()); 
        } 
    } 
}
輸出:
Stack: [1, 2, 3, 10, 20]

Using ListIterator:

Value is : 1
Value is : 2
Value is : 3
Value is : 10
Value is : 20


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack listIterator() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。