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


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


Java.util.Stack.iterator()方法用於返回與Stack相同的元素的迭代器。元素從堆棧中以隨機順序返回。

用法:

Iterator iterate_value = Stack.iterator();

參數:該函數不帶任何參數。


返回值:該方法迭代堆棧的元素並返回值(迭代器)。

以下示例程序旨在說明Java.util.Stack.iterator()方法的使用:

示例1:

// Java code to illustrate iterator() 
  
import java.util.*; 
import java.util.Stack; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<String> stack = new Stack<String>(); 
  
        // Use add() method to add elements into the Stack 
        stack.add("Welcome"); 
        stack.add("To"); 
        stack.add("Geeks"); 
        stack.add("4"); 
        stack.add("Geeks"); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Creating an iterator 
        Iterator value = stack.iterator(); 
  
        // Displaying the values 
        // after iterating through the stack 
        System.out.println("The iterator values are: "); 
        while (value.hasNext()) { 
            System.out.println(value.next()); 
        } 
    } 
}
輸出:
Stack: [Welcome, To, Geeks, 4, Geeks]
The iterator values are: 
Welcome
To
Geeks
4
Geeks

示例2:

// Java code to illustrate hashCode() 
  
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 into the Stack 
        stack.add(10); 
        stack.add(20); 
        stack.add(30); 
        stack.add(40); 
        stack.add(50); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Creating an iterator 
        Iterator value = stack.iterator(); 
  
        // Displaying the values 
        // after iterating through the stack 
        System.out.println("The iterator values are: "); 
        while (value.hasNext()) { 
            System.out.println(value.next()); 
        } 
    } 
}
輸出:
Stack: [10, 20, 30, 40, 50]
The iterator values are: 
10
20
30
40
50


相關用法


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