Prev Next

Java / Queue and its implementations

Could not find what you were looking for? send us the question and we would be happy to answer your question.

Difference between offer and add method in priority queue in java.

The add() will throw an IllegalStateException if no space is currently available in the Queue otherwise add method will return true. offer() method will return false if the element cannot be inserted due to capacity restrictions.

List few Queue implementations.

LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations

The PriorityQueue class is a priority queue based on the heap data structure. This queue orders elements according to the order specified at construction time.

java.util.concurrent package contains a set of synchronized Queue interfaces and classes. More information can be found here.

Explain priority queue in Java.

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or using a Comparator provided at queue construction time, depending on which constructor is used.

A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects and may result in ClassCastException.

Difference between PriorityQueue and TreeSet in Java.

PriorityQueue is a Queue and it provides the functionality of FIFO data structure, while TreeSet is a Set.

TreeSet is a Set that doesn't allow duplicate elements but PriorityQueue may contain duplicates.

The PriorityQueue provides largest or smallest element in O(1) time, which is not possible by TreeSet. Since TreeSet is backed by a red-black tree, the search operation will take O(log N) time.

TreeSet have all elements remain in the sorted order, while in priority queue apart from root, which is guaranteed to be smallest or largest depending upon Comparing logic, rest of element may or may not follow any ordering.

«
»
Regular expressions

Comments & Discussions