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
How to Compile a Java Program. There are two parts to the Java platform, ... How to Program 3D Games in Java;...
How to Create a Java Spreadsheet Data Structure
How to Create a Java Spreadsheet Data Structure. At the simplest level, ... How to Code FIFO in Java. First In First...
How to Use FIFO Buffers
First In-First Out (FIFO) buffers are designed to help Universal Asynchronous Receiver Transmitters (UARTs). ... Look at your modem for the UART...
How to Update Items in a List With Java
import java.util.List; import java.util.ArrayList; ... l.add("First item"); l.add("Second item"); ... Check It Out Parenting With ...
Reasons to Use FIFO in Reporting a Work in Process
First In-First Out (FIFO) buffers are designed to help Universal Asynchronous Receiver Transmitters ... How to Code FIFO in Java. First In...