Queue

  • Eclipse: Oxygen
  • Java: 1.8

The queue is a data structure that First in First Out 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

1

2

3

4

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 queue. add() method is used to add data at the end of the queue.

Output:

1

2

3

4

5

6

When size of queue is exceeded, it throws IllegalStateException.

remove()  method removes the first element of the queue. If we try to remove any 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

1

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

Output

True // 1 is added

false //7 is not added

1

2

3

4

5

6

poll()  is a special method 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 which checks for first element of the  queue. It returns null if implemented on 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 the 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

1

2

3

4

5

6

7

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

0

1

2

3

4

5

6

Special methods for Deque

Contributed by Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu