What`s New in Java 1.5 Tiger? - Using Queues
(Page 2 of 6 )
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.
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 thrown—which 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
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();
}
}
}
In testFIFO(), you can see that the first items into the queue are the first ones out:
[echo] Running QueueTester...
[java] First
[java] Second
[java] Third
As unexciting as that may seem, that’s the bulk of what makes Queue unique—the ordering it provides.
If you’re paying attention, you might wonder about this bit of code, though:
public queue q;
public QueueTester() {
q = new LinkedList();
}
In Tiger, LinkedList has been retrofitted to implement the Queue interface. While you can use it like any other List implementation, it can also be used as a Queue implementation.
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 10—but there is plenty of coverage there.
Next: Ordering Queues Using Comparators >>
More Java Articles
More By O'Reilly Media
|
This article was taken from chapter one of Java 1.5 Tiger: A Developer's Notebook, written by Brett McLaughlin and David Flanagan (O'Reilly, 2004; ISBN: 0596007388). Check it out at your favorite bookstore. Buy this book now.
|
|