Java

TOPIC 22 – JAVA COLLECTIONS IV – QUEUES & STACKS

 

 

LESSON NOTE

 

 

INTRO - STACK

 

A stack is a data structure that holds items in a specific order.  You can only access the top of the stack.  New items are always added to the top of the stack.  Items are always removed from the top of the stack as well.

 

CLASSIC REAL WORLD STACK

 

A classic example of a stack in the real world is a stack of dirty plates.  When you add a plate to the stack, you add it on top.  You keep on adding plates on top.  When it is time to clean the plates, you take the top one off the stack and clean it.  Then you again take the top one on the stack and clean it.  As your cleaning, if another dirty plate arrives, it goes on top the stack. 

 

LIFO & FILO

 

An element that is first in the stack, is last to get out of the queue.  First in, last out.  Or, FILO.

 

Similarly, an element that is last in, is first to get out.  Last in, first out. Or, LIFO.

 

So a queue is said to be either FIFO or LILO.

 

IMPLEMENTATIONS

 

In Java, Stack is a class.  It is an older class.  (It is actually suggested that you use a Deque class instead.  However, Mr. Campeau believes there is value in sticking with the Stack class for learning.)

 

 

EXAMPLE CODE

We create a stack using:

 

    Stack<Integer> stak = new Stack<Integer>();

 

 

FUNCTIONALITY

 

Here are the most important methods for map structures:

 

  • push() – adds an element to the top of the stack
  • pop() – gets and removes the element at the top of the stack
  • peek() – gets the element at the top of the stack (but doesn’t remove it)
  • size() – returns the number of elements in the stack
  • isEmpty() – return true is the stack contains no elements

 

 

EXAMPLE CODE

 

     Stack<Integer> stak = new Stack<Integer>();

     stak.push(54);

     stak.push(19);

     stak.push(34);

     System.out.println(stak);

     stak.pop();

     System.out.println(stak);

 

 

RESULTING OUTPUT

 

[54, 19, 34]

[54, 19]