Java Reference
In-Depth Information
The LinkedList and PriorityQueue are two implementation classes for the Queue interface. Note that the
LinkedList class is also the implementation class for the List interface. The LinkedList class is a multi-purpose
collection implementation class. I will mention its name a few more times in this chapter.
Listing 12-15 demonstrates how to use a LinkedList as a FIFO queue. In fact, it is the Queue interface that
represents a FIFO queue. An instance of the LinkedList class can be used as a FIFO queue or a LIFO queue.
Listing 12-15. Using a FIFO Queue Using LinkedList as the Implementation Class
// QueueTest.java
package com.jdojo.collections;
import java.util.Queue;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class QueueTest {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("John");
// offer() will work the same as add()
queue.offer("Richard");
queue.offer("Donna");
queue.offer("Ken");
System.out.println("Queue: " + queue);
// Let's remove elements until the queuee is empty
while (queue.peek() != null) {
System.out.println("Head Element: " + queue.peek());
queue.remove();
System.out.println("Removed one element from Queue");
System.out.println("Queue: " + queue);
}
// Now Queue is empty. Try calling the peek(),
// element(), poll() and remove() methods
System.out.println("queue.isEmpty(): " + queue.isEmpty());
System.out.println("queue.peek(): " + queue.peek());
System.out.println("queue.poll(): " + queue.poll());
try {
String str = queue.element();
System.out.println("queue.element(): " + str);
}
catch (NoSuchElementException e) {
System.out.println("queue.element(): Queue is empty.");
}
Search WWH ::




Custom Search