❮ Previous Next ❯


Queue implementations:

Being a Collection subtype all methods in the Collection interface are also available in the Queueinterface. Since Queue is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Queue implementations in the Java Collections API:

LinkedList is a pretty standard queue implementation. PriorityQueue stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue. There are also Queue implementations in the java.util.concurrent package, but I will leave the concurrency utilities out of this tutorial.

Here are a few examples of how to create a Queue instance:

Queue q1 = new LinkedList();
Queue q2 = new PriorityQueue();

Adding and Accessing Elements:

To add elements to a Queue you call its add() method. This method is inherited from the Collectioninterface. Here are a few examples:

Queue q1 = new LinkedList();

The order in which the elements added to the Queue are stored internally, depends on the implementation. The same is true for the order in which elements are retrieved from the queue. You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method. Here is how that looks:

Object firstElement = q1.element();
To take the first element out of the queue, you use the remove() method which is described later.You can also iterate all elements of a queue, instead of just processing one at a time. Letís see:
Queue q1 = new LinkedList();
access via Iterator
Iterator iterator = q1.iterator();
String element = (String) iterator.next();

access via new for-loop

for(Object object : q1)
String element = (String) object;

When iterating the queue via its Iterator or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.

Removing Elements:

To remove elements from a queue, you call the remove() method. This method removes the element at the head of the queue. In most Queue implementations the head and tail of the queue are at opposite ends. It is possible, however, to implement the Queue interface so that the head and tail of the queue is in the same end. In that case you would have a stack. The following is a remove example;

Object firstElement =q1.remove();

❮ Previous Next ❯


Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Email: info@silantechnology.com
      Phone: 0674-2361252
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved