A Queue<E> is an ordered Collection of elements of type E. Unlike List, the Queue interface does not permit indexed access to its elements: elements may be inserted at the tail of the queue and may be removed from the head of the queue, but the elements in between may not be accessed by their position. Unlike Set, Queue implementations do not prohibit duplicate elements.

Queues may be manipulated through the methods of the Collection interface, including iteration via the iterator( ) method and the Iterator object it returns. It is more common to manipulate queues through the more specialized methods defined by the Queue interface, however. Place an element at the tail of the queue with offer( ). If the queue is already full, offer( ) returns false. Remove an element from the head of the queue with remove( ) or poll( ). These methods differ only in the case of an empty queue: remove( ) throws an unchecked NoSuchElementException and poll( ) returns null. (Most queue implementations prohibit null elements for this reason, but LinkedList is an exception.) Query the element at the head of a queue without removing it with element( ) or peek( ). If the queue is empty, element( ) throws NoSuchElementException and peek( ) returns null.

Most Queue implementations order their elements in first-in, first-out (FIFO) order. Other implementations may provide other orderings. A queue Iterator is not required to traverse the queue’s elements in order. A Queue implementation ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.