Java中栈的clone()方法及其示例
Stack类的clone()方法用于返回此Stack的浅表副本。它只创建栈的一个副本。该复制品将引用内部数据数组的克隆但不是内部原始数据数组的引用。
语法:
Stack.clone()
参数: 该方法不需要任何参数。
返回值: 该方法返回一个Object,它只是Stack的副本。
异常: 如果对象的类不支持Cloneable接口,则此方法会抛出 CloneNotSupportedException 。
下面的代码演示了Java.util.Stack.clone()方法:
程序1:
// Java code to illustrate clone()
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 another Stack to copy
Object copy_Stack = stack.clone();
// Displaying the copy of Stack
System.out.println("The cloned Stack is: "
+ copy_Stack);
}
}
Stack: [Welcome, To, Geeks, 4, Geeks]
The cloned Stack is: [Welcome, To, Geeks, 4, Geeks]
程序2:
// Java code to illustrate clone()
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 Queue
stack.add(10);
stack.add(15);
stack.add(30);
stack.add(20);
stack.add(5);
// Displaying the Stack
System.out.println("Stack: " + stack);
// Creating another Stack to copy
Object copy_Stack = (Stack)stack.clone();
// Displaying the copy of Stack
System.out.println("The cloned Stack is: "
+ copy_Stack);
}
}
Stack: [10, 15, 30, 20, 5]
The cloned Stack is: [10, 15, 30, 20, 5]
极客教程