13.03. Queue and Dequeue

Queue

  • Eclipse: Oxygen
  • Java: 1.8

The queue is a data structure that First in First Out(FIFO) structure. This is based on the real-life concept of the queue or a line of people. Therefore, this can be very useful in several ways, such as to find the level order traversal in a tree, etc. Therefore, the basic operation of this is shown here.

In the following example, we will create the LinkedBlockingQueue. LinkedBlockingQueue is of dynamic size. It’s not required to provide size while creating LinkedBlockingQueue.

add() method is used to add data at the end of the queue, and we can iterate queue elements using enhanced for loop.

Output

In the following example, we will create ArrayBlockingQueue.

Like Arrays, ArrayBlockingQueue is of fixed size. Size of ArrayBlockingQueue should be provided as arguments while creating a queue. add() method is used to add data at the end of the queue.

Output:

1

2

3

4

5

6

When the size of the queue is exceeded, it throws IllegalStateException.

remove()  method removes the first element of the queue. If we try to remove an element from an empty queue, it throws NoSuchElementException.

element() method returns the first element of the queue. . If we try to examine any empty queue, it throws NoSuchElementException.

Output

offer() is a special method used for adding data into a queue, which returns true if data is successfully added into a queue and false if data is not added.

Output

poll()  is a special method that removes the first element of the queue and returns the element which is removed from the queue. If we try to poll any element from an empty queue, it returns null.

Output

null

1

2

3

4

5

6

removed element from Queue: 1

peek() is also a special method that checks for the first element of the queue. It returns null if implemented on an empty queue.

Output

null

1

2

3

4

5

6

********************

1

Dequeue

This means a DOUBLE ENDED QUEUE. The queue is seen by us previously. The double-ended queue means insertion and deletion can take place from both ends. Therefore, the basic operations of this data structure are shown here.

In the following example, all the Queue methods can be used with Deque, but Deque has its own methods which allow to add and remove elements at the beginning and end of Deque.

Output

Follow the table where special methods are mentioned:

Contributed by Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments