Java Reference
In-Depth Information
Table 12-2 lists the new methods that are declared in the Deque interface to facilitate insertion, removal, and peeking at
either end (head or tail) of a Deque . In the method names, first means head and last means tail.
Table 12-2. New Methods in Deque Interface for Insertion, Removal, and Peek Operations at Both Ends
Category
Method
Description
void addFirst(E)
void addLast(E)
The addXxx() methods add an element at the head
or tail, and they throw an exception if an element
cannot be added, such as in a full bounded Deque .
The offerXxx() methods work the same way as
the addXxx() methods. However, they do not throw
an exception on failure. Rather, they return false if
the specified element cannot be added to a Deque .
Adding an element to the Deque
boolean offerFirst(E)
boolean offerLast(E)
E removeFirst()
E removeLast()
The removeXxx() methods retrieve and remove the
element from the head or tail of the Deque . They
throw an exception if the Deque is empty.
The pollXxx() methods perform the same job as
the removeXxx() methods. However, they return
null if the Deque is empty.
Removing an element from the
Deque
E pollFirst()
E pollLast()
E getFirst()
E getLast()
The getXxx() methods retrieve without removing
the element at the head or the tail of the Deque .
They throw an exception if the Deque is empty.
The peekXxx() methods perform the same job as
the getXxx()methods . However, they return null if
the Deque is empty instead of throwing an exception.
Peeking at an element at end of
the Deque
E peekFirst()
E peekLast()
Since Deque inherits from Queue , a Deque can also act like a FIFO queue. Table 12-3 compares the methods in the
Queue interface and their equivalent methods in the Deque interface.
Table 12-3. Method Comparison of the Queue and Deque Interfaces
Method in Queue
Equivalent Method in Deque
add(e)
addLast(e)
offer(e)
offerLast(e)
remove()
removeFirst()
poll()
pollFirst()
element()
getFirst()
peek()
peekFirst()
Since, in a FIFO queue, you always add an element at the tail (or Last), the add() method in the Queue interface
does the same thing as what the addLast() method does in the Deque interface.
You can also use a Deque as a stack (a LIFO queue) using familiar methods such as push() , pop() , and peek() .
The push() method pushes (or adds) an element to the top of the stack that is the same as using the method
addFirst() . The pop() method pops (or removes) the element from the top of the stack that is the same as calling
 
 
Search WWH ::




Custom Search