Stacks
When we say "last-in-first-out" principle, we mean that the last thing we insert into the stack will be the first thing we retrieve.
Syntax:
Stack<E> stack = new Stack<E>();
This is how we declare stacks in Java. We declared a Stack with the name stack, of type "E", which, in this case, is a place holder for a data type such as Integer or String (or something of the sort).
There are many useful methods that we can do with stacks in Java. These methods will help us add and remove elements, as well as examine our stack.
Method 1:
s.push()
This method will add whatever element is in the parenthesis into the stack. For example, if we have an integer stack with elements {1,2,3,4,5}, and we write s.push(6), the new value of s is
{1,2,3,4,5,6}
Method 2:
s.pop()
This method will remove the last element in the stack. Take the example where we had
s = {1,2,3,4,5}. Then after we take s.pop(), we will get s={1,2,3,4}
Method 3:
s.peek()
This method will return the last element in the stack without adding or removing anything. For example, if we have s={1,2,3,4,5,6}, and we let int x = s.peek(), then x=6.
More Methods:
There are many other more specific methods we can use. For more details, visit the official java library by Oracle!
Iteration: As with any data structure, iteration is always important. How do we iterate through a stack?
Example 1:
{
Stack<Integer> s = new Stack<Integer>();
s.add(1);
s.add(2);
s.add(3);
s.add(4);
for(Integer item: s){
System.out.println(item);
}
}
When we want to iterate over a stack, we can use an enhanced for loop, or "for-each" loop to do so. This will allow us to access all of the elements in the stack with ease.
Exercise(s):
1. Make an integer stack, and copy the contents of the stack to another stack using loops. (Note: how is this different from the exercise with Queues?)