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.
How to Compile a Java Program
There are two parts to the Java platform, the Java application programming interface, or API, and the Java virtual machine, or JVM....
How to Create a Java Spreadsheet Data Structure
At the simplest level, you can create a data structure for a spreadsheet in Java using a simple 2D array. However, this...
How to Update Items in a List With Java
One of the powerful features of the Java programming language is its implementation of many powerful and common data structures (besides the...
How to Use FIFO Buffers
First In-First Out (FIFO) buffers are designed to help Universal Asynchronous Receiver Transmitters (UARTs). UARTs are the chips on internal modem cards....
Reasons to Use FIFO in Reporting a Work in Process
FIFO is a common method for tracking inventory and stands for first-in, first-out. Inventory is categorized three ways: Finished goods, work in...