How to Code FIFO in Java


First In First Out (FIFO) data structures, or queues, allow the programmer to retrieve data from a structure in the order it went in. This can be useful in many situations where the programmer needs a constantly rotating set of data. In many languages, the programmer is left to work this out for himself using either memory address pointers or arrays, but in Java that is unnecessary. The "Queue" interface provides this functionality in a variety of existing classes, and the best choice is the "LinkedList."

  • Open "Netbeans." Click "File" and "New class."

  • Type "psvm" to create a main method.

  • Add the following code to the main method:

    LinkedList<String> fifo = new LinkedList<String>();

    fifo.offer("This is first.");

    fifo.offer("This is second.");

    fifo.offer("This is third.");




    The "offer" method adds the new data to the end of the queue. The "add" method can also be used, and can optionally specify a position in the list for the new element. The "poll" method will both return the item at the head of the queue and remove it from the list entirely. If you want to look at the item at the front of the list, but not have it removed, you would use the "peak" method instead.

Tips & Warnings

  • There are dozens more methods that are part of the LinkedList method. Read about them at the first reference.
  • Because of the way LinkedLists are implemented, it is very inefficient to access data in the middle of the list. Use a LinkedList only if you intend to access data in the order it is in the list, or if the list should remain very small at all times. Read more about why this is at the first resource.

Related Searches


Promoted By Zergnet



You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!