Java Stack copyInto()方法及实例
java.util.Stack.copyInto()方法用于将这个堆栈中的所有元素复制到另一个堆栈中,有足够的空间来容纳堆栈中的所有元素。需要注意的是,元素的索引保持不变。堆栈中存在的元素被堆栈中的元素所取代。
语法
Stack.copyInto(Object Stack[])
参数: 参数Stack[]的类型是Stack。这是一个堆栈,堆栈中的元素将被复制到其中。
返回值: 该方法为无效类型,不返回任何值。
异常: 如果Stack是空的,该方法会抛出NullPointerException。
下面的程序说明了Java.util.Stack.copyInto()方法。
程序1 :
// Java code to illustrate copyInto()
import java.util.*;
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 Stack
String arr[] = new String[6];
arr[0] = "Hello";
arr[1] = "World";
// Displaying the initial Stack
System.out.println("The initial Stack is: ");
for (String str : arr)
System.out.println(str);
// Copying
stack.copyInto(arr);
// The final Stack
System.out.println("The final Stack is: ");
for (String str : arr)
System.out.println(str);
}
}
输出:
Stack: [Welcome, To, Geeks, 4, Geeks]
The initial Stack is:
Hello
World
null
null
null
null
The final Stack is:
Welcome
To
Geeks
4
Geeks
null
示例2
// Java code to illustrate copyInto()
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 Stack
Integer arr[] = new Integer[6];
arr[0] = 50;
arr[1] = 60;
arr[2] = 70;
arr[3] = 80;
arr[4] = 90;
// Displaying the initial Stack
System.out.println("The initial Stack is: ");
for (Integer str : arr)
System.out.println(str);
// Copying
stack.copyInto(arr);
// The final Stack
System.out.println("The final Stack is: ");
for (Integer str : arr)
System.out.println(str);
}
}
输出:
Stack: [10, 20, 30, 40, 50]
The initial Stack is:
50
60
70
80
90
null
The final Stack is:
10
20
30
40
50
null
极客教程