What are the operations on a Java Deque? How does the for each loop iterate through it?
- User
What are the operations on a Java Deque? How does the for each loop iterate through it?
Assistant
A Java Deque (Double-Ended Queue) supports operations at both ends of the collection. Here are the main operations:
Adding elements:
addFirst(e)/offerFirst(e)- adds to the frontaddLast(e)/offerLast(e)- adds to the rearpush(e)- adds to the front (stack operation)add(e)/offer(e)- adds to the rear
Removing elements:
removeFirst()/pollFirst()- removes from the frontremoveLast()/pollLast()- removes from the rearpop()- removes from the front (stack operation)remove()/poll()- removes from the front
Examining elements:
getFirst()/peekFirst()- examines the front elementgetLast()/peekLast()- examines the rear elementpeek()- examines the front elementelement()- examines the front element
The difference between methods like
removeFirst()vspollFirst()is that the former throws an exception if the deque is empty, while the latter returns null.For-each loop iteration:
When you use a for-each loop with a Deque, it iterates from front to rear (head to tail). This is because Deque extends the Collection interface, which provides an iterator that traverses elements in the order they would be returned by repeated calls to
poll().Deque<String> deque = new ArrayDeque<>(); deque.addLast("A"); deque.addLast("B"); deque.addFirst("C"); // Deque now contains: C -> A -> B for (String s : deque) { System.out.println(s); } // Output: // C // A // BThe iteration order is always front-to-rear regardless of how elements were added. If you need reverse iteration, you can use
descendingIterator()method explicitly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.