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]
相關用法
- Java CopyOnWriteArrayList clone()用法及代碼示例
- Java EnumSet clone()用法及代碼示例
- Java RuleBasedCollator clone()用法及代碼示例
- Java EnumMap clone()用法及代碼示例
- Java TreeMap clone()用法及代碼示例
- Java GregorianCalendar clone()用法及代碼示例
- Java LinkedList clone()用法及代碼示例
- Java TreeSet clone()用法及代碼示例
- Java HashSet clone()用法及代碼示例
- Java ArrayDeque clone()用法及代碼示例
- Java LinkedHashSet clone()用法及代碼示例
- Java HashMap clone()用法及代碼示例
- Java ConcurrentSkipListSet clone()用法及代碼示例
- Java IdentityHashMap clone()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack clone() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。