1.2 Using Queues
Another cool collection addition is the java.util.Queue class, for all
those occasions when you need FIFO (first-in, first-out) action. Using this
class is a breeze, and you'll find it's a nice addition to the already robust
Java Collection ...er...collection.NOTESome queues are
LIFO (last-in,
first-out).
1.2.1 How do I do that?
The first thing to realize is that proper use of a Queue implementation is
to avoid the standard collection methods add( ) and remove( ). Instead, you'll need to use offer( ) to
add elements. Keep in mind that most queues have a fixed size. If you call add( ) on a full queue, an unchecked exception is thrownwhich really isn't appropriate, as a queue being full
is a normal condition, not an exceptional one. offer( ) simply returns false if an element cannot be added, which is more in line with standard queue usage.In the same vein, remove( ) throws an exception if the queue is empty; a
better choice is the new poll( ) method,
which returns null if there is nothing in the queue. Both methods attempt to remove elements from the
head of the queue. If you want the head without removing it, use
element( ) or peek( ). Example 1-2 shows these methods in action.
Example 1-2. Using the Queue interface
In testFIFO( ), you can see that the first items into the queue are the
package com.oreilly.tiger.ch01;
import java.io.IOException;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.Queue;
public class QueueTester {
public Queue q;
public QueueTester( ) {
q = new LinkedList( );
}
public void testFIFO(PrintStream out) throws IOException {
q.add("First");
q.add("Second");
q.add("Third");
Object o;
while ((o = q.poll( )) != null) {
out.println(o);
}
}
public static void main(String[] args) {
QueueTester tester = new QueueTester( );
try {
tester.testFIFO(System.out);
} catch (IOException e) {
e.printStackTrace( );
}
}
}
first ones out:
As unexciting as that may seem, that's the bulk of what makes Queue
[echo] Running QueueTester...
[java] First
[java] Second
[java] Third
uniquethe ordering it provides.If you're paying attention, you might wonder about this bit of code,
though:
In Tiger, LinkedList has been retrofitted to implement the Queue interface. While you can use it like any other List implementation, it can also
public Queue q;
public QueueTester( ) {
q = new LinkedList( );
}
be used as a Queue implementation.
NOTEI suppose you file
this under the
"fewer classes
equals less clutter"
theory.
1.2.2 What about...
...using a queue in a concurrent programming environment? This is a
common usage of a queue, when producer threads are filling the queue,
and consumer threads are emptying it. This is more of a threading issue,
and so I've left it for Chapter 10but there is plenty of coverage there.