Stack vs Queue Methods in Java
Comparison of Methods in Queue and Stack in Java
---------------------------------------------------------
| Method | Queue Methods | Stack Methods |
|-----------------------|-------------------------------------|--------------------------------------|
| add(E e) / offer(E e) | add(E e) adds element to the queue | push(E e) adds element to the stack |
| | offer(E e) adds element, returns false on failure | |
| remove() / poll() | remove() removes front element (throws exception if empty) | pop() removes
top element (throws exception if empty) |
| | poll() removes front, returns null if empty | |
| peek() / element() | peek() returns front element (returns null if empty) | peek() returns top
element (returns null if empty) |
| | element() returns front (throws exception if empty) | |
| isEmpty() | isEmpty() returns true if queue is empty | isEmpty() returns true if stack is empty
| size() | size() returns number of elements in queue | size() returns number of elements in
stack |
Queue Example:
---------------
import java.util.Queue;
import java.util.LinkedList;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
System.out.println("Queue size: " + queue.size()); // Output: 2
System.out.println("Head: " + queue.peek()); // Output: Apple
System.out.println("Removed: " + queue.remove()); // Output: Apple
System.out.println("Is queue empty? " + queue.isEmpty()); // Output: false
Stack Example:
--------------
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Apple");
stack.push("Banana");
System.out.println("Stack size: " + stack.size()); // Output: 2
System.out.println("Top: " + stack.peek()); // Output: Banana
System.out.println("Popped: " + stack.pop()); // Output: Banana
System.out.println("Is stack empty? " + stack.isEmpty()); // Output: false