Problem Statement: Create a stack using an ArrayList and implement push, pop, and peek operations.
Here’s a Java program that demonstrates how to create a stack using an ArrayList
and implements the push, pop, and peek operations. I’ll provide an explanation of the program’s logic.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.List;
class Stack<T> {
private List<T> list = new ArrayList<>();
public void push(T item) {
list.add(item);
}
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return list.remove(list.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return list.get(list.size() - 1);
}
public boolean isEmpty() {
return list.isEmpty();
}
public int size() {
return list.size();
}
}
public class StackWithArrayListDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Peek: " + stack.peek());
System.out.println("Stack size: " + stack.size());
System.out.println("Pop: " + stack.pop());
System.out.println("Pop: " + stack.pop());
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
OUTPUT:
Peek: 30
Stack size: 3
Pop: 30
Pop: 20
Is stack empty? false
Explanation:
- Custom Stack Class: We define a generic
Stack
class that wraps anArrayList
to implement the stack operations. The generic typeT
allows the stack to hold elements of any type. - Push Operation: The
push()
method adds an item to the end of theArrayList
, effectively pushing it onto the stack. - Pop Operation: The
pop()
method removes and returns the last item from theArrayList
, simulating the pop operation of a stack. If the stack is empty, it throws anIllegalStateException
. - Peek Operation: The
peek()
method returns the last item from theArrayList
without removing it, simulating the peek operation of a stack. If the stack is empty, it throws anIllegalStateException
. - isEmpty Operation: The
isEmpty()
method checks if theArrayList
is empty, indicating whether the stack is empty. - size Operation: The
size()
method returns the number of items in the stack by querying the size of theArrayList
. - Main Method: We create an instance of the
Stack
class withInteger
type. We perform push operations to add integers to the stack and demonstrate peek, size, and pop operations. We also check if the stack is empty after performing pop operations.
By encapsulating the stack operations within the Stack
class, we can use an ArrayList
as the underlying data structure to implement the stack behavior efficiently.
See also: Sorting a List: Sort an ArrayList of custom objects.