Code: FIFO List in Java
One of the common questions I hear from Java newcomers is - where is a FIFO list in Java?
Java does have a FIFO list capability built-in with LinkedList and ArrayList, but they are not well advertized.
A FIFO interface should at least have:
public interface FIFO {
/** Add an object to the end of the FIFO queue */
boolean add(Object o);
/** Remove an object from the front of the FIFO queue */
Object remove();
/** Return the number of elements in the FIFO queue */
int size();
}
A FIFOList class implementing the above would simply be:
public class FIFOList extends LinkedList implements FIFO {
public Object remove() {
return remove(0);
}
}
I prefer this setup instead of using a LinkedList.remove(0) directly. It looks cleaner.
BTW: You can also extend an ArrayList instead of LinkedList to achieve the same functionality. LinkedList should in theory provide better performance.
Filed under Headline News, How To, Java Software, Tech Note |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |






































February 26th, 2006 at 11:04 am
A nice solution for a FIFO queue is a wrapper around a circular array. Removes at either end are cheap, inserts at either end are also cheap. Memory usage is low and Object allocation is infrequent.
February 26th, 2006 at 7:54 pm
well.. isnt fifo is actually a Queue? there are plenty of Queues available in Java5.
February 27th, 2006 at 9:07 am
You are right. I overlooked them in 1.5. In fact ArrayList also implements Queue.
February 17th, 2008 at 6:14 pm
can you send me a copy of your codes in FIFO which deals with the page(s). please grant me my request..thank you.!!!
April 26th, 2008 at 1:41 pm
You could have just used LinkedList. Method add adds element to the end. And to retrieve element use getFirst
April 27th, 2008 at 1:21 am
As I said before:
“I prefer this setup instead of using a LinkedList.remove(0) directly. It looks cleaner.”
May 25th, 2008 at 6:39 pm
Muchas gracias!
you’r right, it is simple and clear