Skip to the content.

Collections

-

Stack, LinkedList, Queue

- -

What we’ll cover

What is a Stack?

The Stack Interface

Stack Methods

LinkedList

The Queue Interface

Queue Methods

-

Stack

-

What is a Stack?

-

Shortcomings of Java’s Stack class

-

Stack methods

-

isEmpty()

-

isEmpty() example

@Test
public void demo() {
		Stack<String> stack = new Stack<>();
		System.out.println(stack.isEmpty()); // prints true
}

Output

true

-

push()

-

push() example

@Test
public void demo() {
		Stack<String> stack = new Stack<>();
		stack.push("Hello world");
		System.out.println(stack.isEmpty()); // prints false
}

Output

false

-

peek()

-

peek() example

@Test
public void demo() {
		Stack<String> stack = new Stack<>();
		stack.push("Hello world");
		System.out.println(stack.peek());
}

Output

Hello world

-

pop()

-

pop() example

@Test
public void demo() {
		Stack<String> stack = new Stack<>();
		System.out.println(stack.isEmpty()); // prints true
		stack.push("Hello world");
		System.out.println(stack.isEmpty()); // prints false
		String topValue = stack.pop();
		System.out.println(topValue); //prints "Hello World"
		String topValue2 = stack.pop(); // throws EmptyStackException
}

Output

true
false
Hello world

java.util.EmptyStackException
	at java.base/java.util.Stack.peek(Stack.java:102)

-

Stack Methods

-

LinkedList

-

Node

class Node<DataType> {
	DataType data;
	Node next;

	Node(DataType d) {
		data = d;
		next = null;
	}
}

-

LinkedList

class LinkedList<DataType> {
  Node<DataType> head;
}

-

LinkedList

-

Queue Interface

-

Queue Interface

-

Minimal Form of a Queue Interface

// a simplified form of the interface in the standard library
public interface Queue<E> {
	void add(E element);
	E remove();
	E peek();
	int size();
}

-

Queue API Structure

-

Queue API Structure: Adding

-

Queue API Structure
add(e)

-

Queue API Structure
offer(e)

-

Queue API Structure: Removing

-

Queue API Structure
remove()

-

Queue API Structure
poll()

-

Queue API Structure: Viewing

-

Queue API Structure
element()

-

Queue API Structure
peek()

-

Queues, Deques, and Stacks

Note: Deque is often used for stacks as well

-

All About Queues

-