title: How to data be stored in Stack and Queue in java?
body: <p>When i one by one push data in stack and add data in queue then it's stored without sorting but when i am using loop and push these same data in stack and add in queue then data stored as sorted. Another thing is, when i am push data in stack one by one it's store data one by one but for queue it's store data randomly. I can't understand how to be data store in stack and queue ? 
  Here the code:</p>
  
  <pre><code>import java.util.PriorityQueue;
  import java.util.Queue;
  import java.util.Stack;
  
  public class Stack_Queue_RealtionTwo {
  
      public static void main(String[] args) {
  
          Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();
          Queue&lt;Integer&gt; queue = new PriorityQueue&lt;Integer&gt;();
  
          stack.push(5);
          stack.push(2);
          stack.push(3);
          stack.push(1);
          stack.push(4);
          stack.push(6);
  
          queue.add(5);
          queue.add(2);
          queue.add(3);
          queue.add(1);
          queue.add(4);
          queue.add(6);
  
          System.out.println("STACK: " + stack + "\nQUEUE: " + queue);
          System.out.println("\nAFTER POP AND POLL\n");
          System.out.println("STACK: " + stack.pop() + "\nQUEUE: " + queue.poll());
  
          stack.clear();
          queue.clear();
  
          ///using loop
          int[] x = {5, 2, 3, 1, 4, 6};
  
          for (int i = 0; i &lt;= x.length; i++) {
              stack.push(i);
              queue.add(i);
          }
  
          System.out.println("\nSTACK: " + stack + "\nQUEUE: " + queue);
          System.out.println("\nAFTER POP AND POLL\n ");
          System.out.println("STACK: " + stack.pop() + "\nQUEUE: " + queue.poll());
      }
  }
  </code></pre>
  
  <p>OUTPUT IS:</p>
  
  <pre><code>    STACK: [5, 2, 3, 1, 4, 6]
      QUEUE: [1, 2, 3, 5, 4, 6]
  
      AFTER POP AND POLL
  
      STACK: 6
      QUEUE: 1
  
      STACK: [0, 1, 2, 3, 4, 5, 6]
      QUEUE: [0, 1, 2, 3, 4, 5, 6]
  
      AFTER POP AND POLL
  
      STACK: 6
      QUEUE: 0
  </code></pre>