Queue
Published Apr 17, 2022Updated Apr 2, 2023
Contribute to Docs
A Queue
is an interface provided in the java.util
package that extends collections to provide additional methods to access or manipulate items at the head of the queue. Where the “head” of the queue is defined by the particular implementation.
Queue elements are commonly accessed in a FIFO (first-in-first-out) manner. In a priority queue implementation, the first item out will be defined by its specified priority.
Syntax
import java.util.Queue;
Queue<DataType> q = new QueueClass<DataType>();
Where DataType
is the data type to be stored in the queue, and QueueClass
is some class implementing the Queue
interface.
Methods
The Queue
interface utilizes the following methods:
.add(item)
: addsitem
to theQueue
if possible, otherwise it throws an exception..offer(item)
: addsitem
to theQueue
if possible, otherwise it returnsfalse
..remove()
: removes and returns the head item of theQueue
, throwing an exception when theQueue
is empty..poll()
: removes and returns the head item of theQueue
, returningnull
if theQueue
is empty..element()
: returns the head of theQueue
without removing it, throwing an exception when theQueue
is empty..peek()
: returns the head of theQueue
without removing it, returningnull
if theQueue
is empty.
Example
This is an example of the Queue
interface implemented by a LinkedList
:
import java.util.LinkedList;import java.util.Queue;// Main.javapublic class Main {public static void main(String[] args) {Queue<String> food = new LinkedList<String>();food.offer("Cabbage");food.offer("Pizza");food.offer("Sausage");food.offer("Potatoes");food.offer("Salad");System.out.println(food.peek());System.out.println(food.poll());System.out.println(food);}}
This will output the following:
CabbageCabbage[Pizza, Sausage, Potatoes, Salad]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours