當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack 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]


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack clone() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。