Java Queue Interface
The interface Queue is available in the java.util package and does extend the Collection interface. It is used to keep the elements that are processed in the First In First Out (FIFO) manner. It is an ordered list of objects, where insertion of elements occurs at the end of the list, and removal of elements occur at the beginning of the list.
Being an interface, the queue requires, for the declaration, a concrete class, and the most common classes are the LinkedList and PriorityQueue in Java. Implementations done by these classes are not thread safe. If it is required to have a thread safe implementation, PriorityBlockingQueue is an available option.
Queue Interface Declaration
Methods of Java Queue Interface
Features of a Queue
The following are some important features of a queue.
PriorityQueue is also class that is defined in the collection framework that gives us a way for processing the objects on the basis of priority. It is already described that the insertion and deletion of objects follows FIFO pattern in the Java queue. However, sometimes the elements of the queue are needed to be processed according to the priority, that's where a PriorityQueue comes into action.
PriorityQueue Class Declaration
Let's see the declaration for java.util.PriorityQueue class.
Java PriorityQueue Example
FileName: TestCollection12.javaTest it Now
head:Amit head:Amit iterating the queue elements: Amit Jai Karan Vijay Rahul after removing two elements: Karan Rahul Vijay
Java PriorityQueue Example: Book
Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in PriorityQueue, you need to implement Comparable interface.
Traversing the queue elements: 101 Data Communications & Networking Forouzan Mc Graw Hill 4 233 Operating System Galvin Wiley 6 121 Let us C Yashwant Kanetkar BPB 8 After removing one book record: 121 Let us C Yashwant Kanetkar BPB 8 233 Operating System Galvin Wiley 6