Java中的堆栈迭代器()方法与示例
Java.util.Stack.iterator()方法用于返回与堆栈相同元素的迭代器。元素从堆栈中的内容以随机顺序返回。
句法:
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 stack = new Stack();
// 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 stack
= new Stack();
// 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