|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Using a Queue (or LinkedList)
The Queue interface implements the Collection interface and supports ordering on a FIFO (First In First Out) basis. This means that when you start out with an empty queue object and add an item to it, that object will be the first to be removed when using any of the methods that supports removing of items from the queue. The main difference between a List and a Queue is that in the former you can choose what item to get, while in a Queue you only get access to the "first in line" object (however this shouldn't be confused with classes like LinkedList which implements both the Queue and List interfaces). In this example we use the LinkedList class which implements the Queue interface and add items to it using both the add() and offer() methods. The difference between them is that the add method will throw an exception should the adding of the item fail but the offer() method will simply return false. The example also shows how to remove items from the queue by using any of the two methods for removing, remove() and poll(). Like the methods to add items there's one method that throws and exception if the remove operation goes wrong (i.e. if the queue is empty) and one that only returns false. The same goes for the two methods for checking what item is first in the queue without removing it. |
import java.util.LinkedList; import java.util.Queue; /** * * @author javadb.com */ public class Main { /** * Example method for using a Queue */ public void queueExample() { Queue queue = new LinkedList(); //Using the add method to add items. //Should anything go wrong an exception will be thrown. queue.add("item1"); queue.add("item2"); //Using the offer method to add items. //Should anything go wrong it will just return false queue.offer("Item3"); queue.offer("Item4"); //Removing the first item from the queue. //If the queue is empty a java.util.NoSuchElementException will be thrown. System.out.println("remove: " + queue.remove()); //Checking what item is first in line without removing it //If the queue is empty a java.util.NoSuchElementException will be thrown. System.out.println("element: " + queue.element()); //Removing the first item from the queue. //If the queue is empty the method just returns false. System.out.println("poll: " + queue.poll()); //Checking what item is first in line without removing it //If the queue is empty a null value will be returned. System.out.println("peek: " + queue.peek()); } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().queueExample(); } } |
The output from the code below is: |
remove: item1 element: item2 poll: item2 peek: Item3 |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
