Heaps

less than 1 minute read

Heaps (Priority Queues in Java)

Heaps are implemented using the PriorityQueue class in Java.

  • Efficient Seek Time: Provides O(1) time complexity for accessing the highest priority element.
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    pq.add(10);
    pq.add(20);
    pq.add(15);
    System.out.println("Highest priority element: " + pq.peek());
    
  • Null Elements: Does not allow null elements.
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    pq.add(null); // throws NullPointerException
    
  • Element Ordering: Elements are ordered based on their natural ordering or by a Comparator specified at the time of queue construction.
    PriorityQueue<Integer> naturalOrderQueue = new PriorityQueue<>();
    PriorityQueue<Integer> customOrderQueue = new PriorityQueue<>(Comparator.reverseOrder());
    

Heap as a Priority Queue in java

Methods :

  • add(E e) Inserts the specified element into this priority queue.
  • offer(E e) Inserts the specified element into this priority queue
  • poll()Retrieves and removes the head of this queue, or returns null if this queue is empty.