title: Creating a toString within a queue of two stacks
body: <p>I have created a queue using two stacks from a stack class that i have created. I am wondering if it is possible to be able to read out all of the elements in the queue in order without them being lost from the stack? </p>
  
  <p>The question is: Can i create a toString inside MyQueue.java that will list the order of the queue. </p>
  
  <p>Here are my two files </p>
  
  <p>MyQueue.java </p>
  
  <pre><code>import java.util.NoSuchElementException;
  
  public class MyQueue&lt;T&gt; {
     private MyStack&lt;T&gt; stack1;    // back of queue
     private MyStack&lt;T&gt; stack2;    // front of queue
  
      public MyQueue() {
           stack1 = new MyStack&lt;T&gt;();
           stack2 = new MyStack&lt;T&gt;();
      }
  
  
      private void moveStack1ToStack2()throws Exception {
          while (!stack1.isEmpty())
              stack2.push(stack1.pop());
      }
  
      public boolean isEmpty() {
          return stack1.isEmpty() &amp;&amp; stack2.isEmpty();
      }
  
      public T peek() throws Exception {
          if (isEmpty()) throw new NoSuchElementException("Queue underflow");
          if (stack2.isEmpty()) moveStack1ToStack2();
          T result = stack2.peek();
          return result;
      }
  
      // add the item to the queue
      public void enqueue(T item) throws Exception
      {
          stack1.push(item);
      }
  
      public T dequeue() throws Exception  {
          if (isEmpty()) throw new NoSuchElementException("Queue underflow");
          if (stack2.isEmpty())
          {
            moveStack1ToStack2();
          }
          return (T)stack2.pop();
      }
      public int size()
      {
        return stack1.size() + stack2.size();
      }
  
  
  }
  </code></pre>
  
  <p>MyStack.java</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.EmptyStackException;
  
  public class MyStack&lt;T&gt; {
      private ArrayList&lt;T&gt; al;
  
      public MyStack() {
          al = new ArrayList&lt;T&gt;();
      }
  
      public void push(T item) {
          al.add(item);
      }
  
      public T pop() {
          if (!isEmpty())
              return al.remove(size()-1);
          else
              throw new EmptyStackException();
      }
  
      public boolean isEmpty() {
          return (al.size() == 0);
      }
  
      public T peek()
    {
          if (!isEmpty())
              return al.get(size()-1);
          else
              throw new EmptyStackException();
      }
  
      public int size() {
          return al.size();
      }
  
      public String toString()
    {
          return al.toString();
      }
  }
  </code></pre>