FIFO class in Java
Try ArrayDeque
or LinkedList
, which both implement the Queue
interface.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
You're looking for any class that implements the Queue interface, excluding PriorityQueue
and PriorityBlockingQueue
, which do not use a FIFO algorithm.
Probably a LinkedList using add
(adds one to the end) and removeFirst
(removes one from the front and returns it) is the easiest one to use.
For example, here's a program that uses a LinkedList to queue and retrieve the digits of PI:
import java.util.LinkedList;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
LinkedList<Integer> fifo = new LinkedList<Integer>();
for (int i = 0; i < arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.removeFirst() + ".");
while (! fifo.isEmpty())
System.out.print (fifo.removeFirst());
System.out.println();
}
}
Alternatively, if you know you only want to treat it as a queue (without the extra features of a linked list), you can just use the Queue
interface itself:
import java.util.LinkedList;
import java.util.Queue;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
Queue<Integer> fifo = new LinkedList<Integer>();
for (int i = 0; i < arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.remove() + ".");
while (! fifo.isEmpty())
System.out.print (fifo.remove());
System.out.println();
}
}
This has the advantage of allowing you to replace the underlying concrete class with any class that provides the Queue
interface, without having to change the code too much.
The basic changes are to change the type of fifo
to a Queue
and to use remove()
instead of removeFirst()
, the latter being unavailable for the Queue
interface.
Calling isEmpty()
is still okay since that belongs to the Collection
interface of which Queue
is a derivative.