how to create a clone of a Stack using collections in java
Previous | Home | Next |
In this example we are going to created a clone of a given Stack.
In this example we will create a stack. For creating a stack we have import the java.util package which contains the java.util.Stack class. In the following example we have created a class named CollectionExample in which we have created a Stack object and added some elements to it.
For creating the clone of the given stack we have created a method named,
Createclone(Stack st, Stack st1)
This method takes two Stack object as arguments, out of the two stack one stack is filled and other is empty.
We have used the clone() method for creating the clone of a Stack whose syntax is given as,
Object clone()
This method creates a shallow copy of the current Stack.
In this example we have created a Stack and to which we have added some elements by using the push(Obejct obj) method on the object of the Stack. We have also created another stack which is empty, then we have called the Createclone(Stack st, Stack st1) method which creates a clone of the Stack st to the Stack st1 by using the clone() method.
package r4r.co.in;
import java.util.*;
public class CollectionExample
{
/**
* @param args
*/
public static void main(String args[]) throws EmptyStackException
{
try
{
Stack<Integer> stck=new Stack<Integer>(); // creating a new stack
stck.push(1); // pushing element onto the stack
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
stck.push(7);
System.out.println("After pushing elements on to the stack its status is: "+stck); // displaying the contents of the stack
int srchele=stck.search(3); // here we are searching which element is at index 3
System.out.println("The searched element is: "+srchele); // displaying the searched element
Stack<Integer> stck1=null; // created a Stack reference variable intialized to null
Createclone(stck, stck1); // calling the Createclone method
}
catch(EmptyStackException e)
{
e.printStackTrace();
}
}
/* The following method created a clone of a given Stack to some another stack */
private static void Createclone(Stack<Integer> st, Stack<Integer> st1)
{
st1=(Stack<Integer>)st.clone();
System.out.println("The elements of the cloned Stack are as follows: ");
Iterator<Integer> itr=st1.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
/* The above method created a clone of a given Stack to some another stack */
}
The output of the above example is as follows:
After pushing elements on to the stack its status is: [1, 2, 3, 4, 5, 6, 7]
The searched element is: 5
The elements of the cloned Stack are as follows:
1
2
3
4
5
6
7
Previous | Home | Next |