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:
Insertion Operations:
addFirst(e)/offerFirst(e)- adds element at the beginningaddLast(e)/offerLast(e)- adds element at the endpush(e)- pushes element at the beginning (stack operation)
Removal Operations:
removeFirst()/pollFirst()- removes and returns first elementremoveLast()/pollLast()- removes and returns last elementpop()- removes and returns first element (stack operation)
Retrieval Operations:
getFirst()/peekFirst()- returns first element without removinggetLast()/peekLast()- returns last element without removingpeek()- returns first element without removing
Other Operations:
size()- returns number of elementsisEmpty()- checks if deque is emptycontains(o)- checks if element existsclear()- removes all elements
The difference between methods like
addFirst()vsofferFirst()is thataddmethods throw exceptions when they fail, whileoffermethods return false. Similarly,removethrows exceptions whilepollreturns null.For-Each Loop Iteration:
The for-each loop iterates through a Deque from first to last element in the order they would be removed by repeated calls to
removeFirst()orpoll().Deque<String> deque = new ArrayDeque<>(); deque.addFirst("A"); // deque: [A] deque.addLast("B"); // deque: [A, B] deque.addFirst("C"); // deque: [C, A, B] // For-each iterates: C -> A -> B for (String element : deque) { System.out.println(element); }This iteration order is defined by the
iterator()method, which the for-each loop uses internally. If you need reverse iteration (last to first), you would usedescendingIterator():Iterator<String> descIt = deque.descendingIterator(); while (descIt.hasNext()) { System.out.println(descIt.next()); // Prints: B -> A -> C }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.