Support Forums

Full Version: Teaching Queues!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A Queue is a collection class released in Java 5 as a design that hold elements and processes them in a particular order. Many implementations of Queue use an order were the elements which are submitted first, are processed first (First in, First out - FIFO). But its not limited to this order.

To start off, we are going to use a Queue to process three different numbers. In this example we are going to use ArrayQueue as the fastest and most straight-forward implementation of this Queue. No need going into advanced topics for anything this simple. With ArrayQueue you get a good FIFO order.

First we import the Queue interface,
Code:
import java.util.ArrayDeque;
import java.util.Queue;

Next we want to actually implement the Queue into our program,
Code:
Queue<E> aQueue = new ArrayDeque<E>();
Since E represents a specified element, we could use an object. Like so,
Code:
Queue<Object> aQueue = new ArrayDeque<Object>();

Now then. There are a small number of methods for use in the Queue interface, however they are very useful for controlling your Queue. Here is the API,
http://java.sun.com/j2se/1.5.0/docs/api/...Queue.html
As you can see, the majority of these methods include using the head of the Queue. The head of the Queue basically means the front, or the beginning.

Now lets get back to our Queue, first we implemented our Queue as an ArrayDeque and we can now start adding elements using offer(E) or add(). Its basically the same way you would add elements using an ArrayList or another Collection class. Like so,
Code:
taskQueue.add("y0");
or
Code:
taskQueue.offer("sup);
And to display the elements its as simple an an enchanced-for loop.

Here is an example program that adds elements to a Queue in FIFO order and displays them using the enchanced-for.
Code:
public class QueueExample {

    public static void main(String[] args) {
        Queue<Number> taskQueue = new ArrayDeque<Number>(); // accepts a Number object
            taskQueue.add(0); // we can use either add() or offer()
            taskQueue.offer(1); // to add elements to the queue
            taskQueue.offer(5.5);

        for (Number printQueue : taskQueue) // Number: printQueue, prints what is in our Queue
            System.out.println(printQueue);
    }

}

Dont know what object Number is? Just ask. ;)
As you can see, this can be VERY effective for many ideas. And for those RSPS programmers, this would be a good idea for a variety of mini-games.

Thanks for reading.