Junior — Middle
What methods of extracting an element from a queue do you know?
sobes.tech AI
Answer from AI
In Java, there are several main methods for extracting an element from a queue (Queue):
- poll() — retrieves and removes the head of the queue, returns null if the queue is empty.
- remove() — retrieves and removes the head of the queue, but throws a NoSuchElementException if the queue is empty.
- peek() — returns the head of the queue without removing it, returns null if the queue is empty.
- element() — returns the head of the queue without removing it, throws a NoSuchElementException if the queue is empty.
Example:
Queue<String> queue = new LinkedList<>();
queue.add("first");
queue.add("second");
String head = queue.poll(); // retrieves "first" and removes it from the queue
System.out.println(head); // first
String next = queue.peek(); // returns "second" without removing it
System.out.println(next); // second