import java.util.ArrayList; import java.util.Collections; import java.util.Stack; /** * Small class illustrating the difference between a deep and a shallow copy **/ public class CopyObject { private Stack stack; /** * Create an instance containing a stack **/ public CopyObject(int size) { stack = new Stack<>(); for (int i=0; i sCopy = stack; // shallow copy while (!sCopy.empty()){ sb.append(sCopy.pop()); if (!sCopy.empty()) sb.append(" "); } return sb.toString(); } /** Driver method **/ public static void main(String[] args){ CopyObject co = new CopyObject(10); System.out.println("First " + co.toString()); System.out.println("Second " + co.toString()); } /** * Deep copy technique 1 * Make a new stack and get all of the objects into the stack **/ private Stack copyStack1(){ Stack newStack = new Stack<>(); ArrayList ali = new ArrayList<>(); while (!stack.isEmpty()) ali.add(stack.pop()); for (Integer ii : ali) { stack.push(ii); newStack.push(ii); } return newStack; } /** * Deep copy technique 2. * The same effect as technique 1 but using java Colletions to make the copy. **/ private Stack copyStack2() { Stack newStack = new Stack<>(); Collections.copy(newStack, stack); return newStack; } }