Java Collection – Java Queue Interface

In the article, JavaSampleApproach will introduce you about Queue interface in Java and give you sample for practice.

A. Concept

1. What is Java Queue?

Queue is a special collection, with a FIFO(First In – First Out) principle to process elements.
Java provides a Queue interface:

2. Queue Methods

Insert operators: add(E e) & offer(E e)
Both add() & offer() methods are used for insertion an element to a Queue if it is possible to do so immediately without violating capacity restrictions. Then returns true if successfully.
In fail case: offer() method will return false. But add() method will throw an exception:
throws IllegalStateException if reason due to capacity restrictions
throws ClassCastException if reason due to the cast type of element’s class
throws NullPointerException if the specified element is null
throws IllegalArgumentException if some property of this element prevents it from being added to this queue

Remove operators: remove() & poll()
Both remove & poll() methods are used to retrieve & remove the head of a queue.
If the queue is not empty, result will be return is the head element of the queue.
Otherwise, remove() method will throw NoSuchElementException, but poll() method will return null.

Retrieve operators: element() & peek()
Retrieve a head element of a queue but not remove it.
In case, the queue is empty, element() method will throw NoSuchElementException, but peek() will return null.

B. Practice

I. Technologies

– Java 8 (Others version is okay)
– Editor: Eclipse

II. Overview
1. Project Structure

java queue structure project

2. Step to do

Practices with:
– Insert Operators
– Retrieve Operators
– Remove Operators
– Behaviour of retrieve & remove operators when Queue is empty
– Run & check result

III. Practice
1. Insert operators

2. Retrieve Operators

3. Retrieve and Remove Operators

4. Behaviour of retrieve operators when Queue is Empty

5. Run & Check result

Full source code:

Run & result:

IV. Sourcecode

Java Queue

Related Posts

    Got Something To Say:

    Your email address will not be published. Required fields are marked *