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


Java Stack copyInto()用法及代碼示例


java.util.Stack.copyInto()方法用於將所有組件從此Stack複製到另一個Stack,並具有足夠的空間來容納Stack的所有組件。要注意的是,元素的索引保持不變。堆棧中存在的元素被堆棧中的元素替換。

用法:

Stack.copyInto(Object Stack[])

參數:參數Stack []的類型為Stack。這是將堆棧中的元素複製到的堆棧。


返回值:該方法為void類型,不返回任何值。

異常:如果Stack為NULL,則該方法引發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


相關用法


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