Sobes.tech
Junior — Middle

Can you explain the key features of the peek method and how it is used in data structures?

sobes.tech AI

Answer from AI

The peek method (often found as peek() or peekFirst(), peekLast() in Java collections) allows you to look at an element in the data structure without removing it.

For example, in a stack, peek() returns the top element without removing it, and in a queue — the element at the front.

This is useful when you need to know which element will be processed next, but want to keep the data structure unchanged.

Example using a stack:

Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);

int top = stack.peek(); // returns 20, but the element remains in the stack
System.out.println(top); // 20
System.out.println(stack.size()); // 2

Thus, peek is a safe way to look into the data structure without modification.