当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。