📜  Java中的堆栈listIterator()方法与示例

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

Java中的堆栈listIterator()方法与示例

Java.util.Stack类的 listIterator ()方法用于返回此堆栈中元素的列表迭代器(以正确的顺序)。返回的列表迭代器是快速失败的。

句法:

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
            Stack
                stack = new Stack();
  
            // 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
            // using listIterator() method
            ListIterator
                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

方案二:

// Java code to illustrate lastIndexOf()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // 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
        // using listIterator() method
        ListIterator
            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