Introduction

Queue interface is a subtype of the java.util.Collection interface. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. Being a Collection subtype all methods in the Collection interface are also available in the Queue interface. Since Queue is an interface you need to instantiate a concrete implementation of the interface in order to use it. Following are Queue implementations in the Java Collections API:

  • java.util.LinkedList
  • java.util.PriorityQueue

Modifying Elements

To add elements to a Queue you call its add() method. This method is inherited from the Collection interface. You can peek at the element at the head of the queue without taking the element out of the queue. To take the first element out of the queue, you use the remove() method.

// Generic queue, MyObject is user defined class
Queue<MyObject> queue = new LinkedList<MyObject>();

Queue queueA = new LinkedList();

queueA.add("element 1");

// Access via Iterator
Iterator iterator = queueA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}

Important API

  • peek()
    Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  • poll()
    Retrieves and removes the head of this queue, or returns null if this queue is empty.
  • isEmpty()
    Returns true if this collection contains no elements.
  • iterator()
    Returns an iterator over the elements in this collection.
  • remove()
    Removes a single instance of the specified element from this collection, if it is present (optional operation).
  • size()
    Returns the number of elements in this collection.
  • Object[] toArray()
    Returns an array containing all of the elements in this collection. This method allocate a new array. so caller is thus free to modify the returned array.
  • boolean contains(Object o)
    Returns true if this collection contains the specified element.
  • boolean equals(Object o)
    Compares the specified object with this collection for equality, returns true if the specified object is equal to this collection