The java.util.Stack.copyInto() method is used to copy all of the components from this Stack to another Stack, having enough space to hold all of the components of the Stack. It is to be noted that the index of the elements remains unchanged. The elements present in the Stack are replaced by the elements of the Stack.
Syntax:
Stack.copyInto(Object Stack[])
Parameters: The parameter Stack[] is of the type of Stack. This is the Stack into which the elements of the Stack are to be copied.
Return Value: The method is of void type and does not return any values.
Exception: The method throws NullPointerException if the Stack is NULL.
Below programs illustrates the Java.util.Stack.copyInto() method:
Program 1:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.add( "Welcome" );
stack.add( "To" );
stack.add( "Geeks" );
stack.add( "4" );
stack.add( "Geeks" );
System.out.println( "Stack: " + stack);
String arr[] = new String[ 6 ];
arr[ 0 ] = "Hello" ;
arr[ 1 ] = "World" ;
System.out.println( "The initial Stack is: " );
for (String str : arr)
System.out.println(str);
stack.copyInto(arr);
System.out.println( "The final Stack is: " );
for (String str : arr)
System.out.println(str);
}
}
|
Output:
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
Program 2:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> stack = new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
stack.add( 50 );
System.out.println( "Stack: " + stack);
Integer arr[] = new Integer[ 6 ];
arr[ 0 ] = 50 ;
arr[ 1 ] = 60 ;
arr[ 2 ] = 70 ;
arr[ 3 ] = 80 ;
arr[ 4 ] = 90 ;
System.out.println( "The initial Stack is: " );
for (Integer str : arr)
System.out.println(str);
stack.copyInto(arr);
System.out.println( "The final Stack is: " );
for (Integer str : arr)
System.out.println(str);
}
}
|
Output:
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Dec, 2018
Like Article
Save Article