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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。