Queue is empty java

Interface Queue

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements’ natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll() . In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

The offer method inserts an element if possible, otherwise returning false . This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or «bounded») queues.

The remove() and poll() methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue’s ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null .

The element() and peek() methods return, but do not remove, the head of the queue.

The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the BlockingQueue interface, which extends this interface.

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList , do not prohibit insertion of null . Even in the implementations that permit it, null should not be inserted into a Queue , as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object , because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

This interface is a member of the Java Collections Framework.

Источник

Interface Queue

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements’ natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll() . In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

The offer method inserts an element if possible, otherwise returning false . This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or «bounded») queues.

Читайте также:  Php фигурные скобки переменные

The remove() and poll() methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue’s ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null .

The element() and peek() methods return, but do not remove, the head of the queue.

The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the BlockingQueue interface, which extends this interface.

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList , do not prohibit insertion of null . Even in the implementations that permit it, null should not be inserted into a Queue , as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object , because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

This interface is a member of the Java Collections Framework.

Источник

Queue Implementation in Java [Updated 2023]

The concept of a Queue data structure is similar to the queue we come across in our day-to-day life like at a bus stop.

and you have to wait until your number arrives, right?

That’s how Queue in Java also works. Whoever is first, is going to get the ticket first.

Hence we can say that the Queue’s working principle is based on First-In-First-Out(FIFO).

queue implementation in Java

A Queue is a linear data structure in which elements are inserted from one end called the Rear and are removed from the other end called the Front.

The value of both the Rear and Front is set to -1 initially and then these values are incremented or decremented as the elements are inserted and deleted.

Basic Functions of Queue

enqueue : It is used to add an element at the rear of the queue.

Читайте также:  Ssh web client php

dequeue : It is used to remove an element from the front of the queue.

IsEmpty : It is used to check whether the queue is empty or not.

IsFull : It is used to check whether the queue is full or not.

peek : It is used to return the front value without removing it.

The complexity of enqueue and dequeue operations in a queue using an array is O(1) .

Although the use of all kinds of abstract data types such as Stack, Queue, and LinkedList is provided in Java it is always desirable to understand the basics of the data structure and implement it accordingly.

1. Queue Implementation using Array in Java

So here we will implement a queue data structure using an array in Java.

import java.util.*; // define queue class class Queue < int arr[], front, rear, cap, n1; // Queue constructor Queue(int n) < arr = new int[n]; cap = n; front = 0; rear = -1; n = 0; >// dequeue function for removing the front element public void dequeue() < // check for queue underflow if (isEmpty()) < System.out.println("No items in the queue,cannot delete"); System.exit(1); >System.out.println("Deleting " + arr[front]); front = (front + 1) % cap; n1--; > // enqueue function for adding an item to the rear public void enqueue(int val) < // check for queue overflow if (isFull()) < System.out.println("OverFlow!!Cannot add more values"); System.exit(1); >System.out.println("Adding " + val); rear = (rear + 1) % cap; arr[rear] = val; n1++; > // peek function to return front element of the queue public int peek() < if (isEmpty()) < System.out.println("Queue empty!!Cannot delete"); System.exit(1); >return arr[front]; > // returns the size of the queue public int size() < return n1; >// to check if the queue is empty or not public Boolean isEmpty() < return (size() == 0); >// to check if the queue is full or not public Boolean isFull() < return (size() == cap); >// Queue implementation in java public static void main (String[] args) < // create a queue of capacity 5 Queue q = new Queue(5); q.enqueue(10); q.enqueue(20); q.enqueue(30); System.out.println("Front element is: " + q.peek()); q.dequeue(); System.out.println("Front element is: " + q.peek()); System.out.println("Queue size is " + q.size()); q.dequeue(); q.dequeue(); if (q.isEmpty()) System.out.println("Queue Is Empty"); else System.out.println("Queue Is Not Empty"); >>

Adding 10
Adding 20
Adding 30
Front Element is:10
Deleting 10
Front Element is:20
Queue size is 2
Deleting 20
Deleting 30
Queue is empty

Also Read: Queue Interface in Java

2. Queue Implementation using Queue Interface in Java

Queue interface is a part of Java Collections that consists of two implementations:

LinkedList and PriorityQueue are the two classes that implement the Queue interface. If you are not aware of what is Queue Interface then you must check it out here.

Queue implementation using Queue Interface in java

Since the Queue is an interface, we cannot create an instance of it. Hence we create the instance of the LinkedList and the PriorityQueue class and assign it to the queue interface.

Queue q1 = new LinkedList(); Queue q2 = new PriorityQueue();

There are mainly five operations of the Queue interface. They are:

boolean add(E e) : This method is used to add a specific element at the end of the queue. Since its return type is boolean, it returns true if the element is added successfully else return false.

Читайте также:  Добавить свойства css через js

E element() : This method returns the first element of the queue.

E remove() : This method removes the first element of the queue.

E poll() : This method is similar to that of a remove() , but the only difference is that the poll returns null if the queue is empty.

E peek() : This method is similar to that of an element() , but the only difference is that element returns null if the queue is empty.

Let us learn these operations using examples:

i) Queue Implementation using Linked List in Java

import java.util.*; public class QueueExample1 < public static void main(String[] args) < Queueq = new LinkedList(); //Adding elements to the Queue q.add("Mohit"); q.add("Priyanka"); q.add("Prabhat"); q.add("Pranjal"); q.add("Anilanshu"); System.out.println("Elements in Queue:"+q); System.out.println("Removed element: "+q.remove()); System.out.println("Head: "+q.element()); System.out.println("poll(): "+q.poll()); System.out.println("peek(): "+q.peek()); System.out.println("Elements in Queue:"+q); > >

Elements in Queue:[Mohit, Priyanka, Prabhat, Pranjal, Anilanshu]
Removed element: Mohit
Head: Priyanka
poll(): Priyanka
peek(): Prabhat
Elements in Queue:[Prabhat, Pranjal, Anilanshu]

ii) Queue Implementation using Priority Queue in Java

import java.util.*; public class QueueExample2 < public static void main(String[] args) < Queueq2 = new PriorityQueue(); //Adding elements to the Queue q2.add(10); q2.add(20); q2.add(30); q2.add(40); q2.add(50); System.out.println("Elements in Queue:"+q2); System.out.println("Removed element: "+q2.remove()); System.out.println("Head: "+q2.element()); System.out.println("poll(): "+q2.poll()); System.out.println("peek(): "+q2.peek()); System.out.println("Elements in Queue:"+q2); > >

Elements in Queue:[10,20,30,40,50]
Removed element: 10
Head: 20
poll(): 20
peek(): 30
Elements in Queue:[30,40,50]

Conclusion

Implementing a queue in Java is a valuable skill for any developer aiming to build efficient and scalable applications. By understanding the various implementations, such as the LinkedList-based Queue, ArrayDeque, and PriorityQueue, you can choose the one that best fits your requirements.

With this, we have covered the Queue Data Structure in Java. We will be covering the other Data Structures too. Happy Learning.

If we missed any function, please do share it with us in the comment section.

Frequently Asked Questions(FAQs)

1. What is queue implementation in Java?

Queue implementation in Java is nothing but the way we can implement Queue in Java programming language. We can implement by many ways, such as:

  1. Queue Implementation using Array in Java
  2. Queue Implementation using Queue Interface in Java
  3. Queue Implementation using Linked List in Java
  4. Queue Implementation using Priority Queue in Java

2. What is Java simplest queue implementation?

Java provides AbstractQueue implementation which is the simplest of them all.

3. Is queue a LIFO or FIFO?

As we’ve seen in the introduction of this article, Queue is a FIFO means First In First Out.

4. How do I remove elements from a queue in Java?

To remove elements from a queue in Java, you can use the remove() , poll() , or dequeue() methods. These methods remove elements from the front of the queue.

5. Can a queue be resized dynamically in Java?

Yes, in Java, certain queue implementations, such as ArrayDeque, automatically resize themselves when the number of elements exceeds their capacity. This dynamic resizing ensures efficient memory management and accommodates varying amounts of data.

You may also like:

Источник

Оцените статью