📜  Java中的堆栈copyInto()方法与示例

📅  最后修改于: 2022-05-13 01:55:44.101000             🧑  作者: Mango

Java中的堆栈copyInto()方法与示例

Java.util.Stack.copyInto()方法用于将所有组件从该堆栈复制到另一个堆栈,有足够的空间容纳堆栈的所有组件。需要注意的是,元素的索引保持不变。 Stack 中的元素被 Stack 中的元素替换。

句法:

Stack.copyInto(Object Stack[])

参数:参数Stack[]是Stack的类型。这是要复制堆栈元素的堆栈。

返回值:该方法为void类型,不返回任何值。

异常:如果 Stack 为 NULL,该方法将抛出NullPointerException

下面的程序说明了Java.util.Stack.copyInto() 方法:

方案一:

// Java code to illustrate copyInto()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // 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

方案二:

// Java code to illustrate copyInto()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // 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