Queue
KyraThompson73 total contributions
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]
All contributors
- KyraThompson73 total contributions
- StevenSwiniarski474 total contributions
- course170094706014 total contributions
- elmanorc3 total contributions
Looking to contribute?
- 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.