title: How can I make a copy of a stack but preserve the original?
body: <p>How can I make a copy of a stack but preserve the original using only <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>isEmpty</code> methods from the Stack class? Is this even possible?</p>
  
  <pre><code>public static &lt;E&gt; Stack&lt;E&gt; copy(Stack&lt;E&gt; s){
  
          s2 = new Stack&lt;E&gt;();
          if(s.isEmpty())
              return null;
  
          while(!s.isEmpty())
          {
              E elem = s.peek();
              s2.push(elem);
              s.pop();
          }
  
          return s2;
      }
  
      public static void main(String[] args) {
  
          StackCopy sCopy = new StackCopy();
  
          Stack&lt;Integer&gt; s = new Stack&lt;Integer&gt;();
  
          s.push(1);
          s.push(2);
          s.push(3);
          s.push(4);
          s.push(5);
  
          s2 = sCopy.copy(s);
  
                  System.out.print("stack1 = ");
                  while(!s.isEmpty()){
              System.out.print(s.peek() );
              s.pop();
          }       
  
                  System.out.println("Stack 2 = ");
          while(!s2.isEmpty()){
              System.out.print(s2.peek() );
              s2.pop();
          }
  
  
      }
  </code></pre>