Java PriorityQueue Class: A Beginner's Guide

Introduction

Hello, future Java programmers! Today, we're going to dive into the wonderful world of PriorityQueue in Java. Don't worry if you've never heard of it before – we'll start from scratch and work our way up together. Think of a PriorityQueue as a special kind of line (or queue) where the most important person (or item) always gets to go first. Exciting, right? Let's get started!

Java - PriorityQueue

Class Declaration

In Java, the PriorityQueue class is part of the Java Collections Framework. It's like a VIP list for your data! Here's how you declare it:

import java.util.PriorityQueue;

PriorityQueue<ElementType> pq = new PriorityQueue<>();

Replace ElementType with whatever type of data you want to store, like Integer, String, or even your own custom objects (but we'll get to that later).

Parameters

When creating a PriorityQueue, you can specify a few optional parameters:

  1. Initial capacity: How many items it can hold initially.
  2. Comparator: A special object that decides the order of elements.

Here's an example:

PriorityQueue<Integer> pq = new PriorityQueue<>(10, Collections.reverseOrder());

This creates a PriorityQueue that can initially hold 10 integers, and they'll be ordered from highest to lowest.

Class Constructors

PriorityQueue comes with several constructors. Think of constructors as different recipes for creating your queue. Here are the main ones:

Constructor Description
PriorityQueue() Creates an empty queue with default initial capacity (11)
PriorityQueue(int initialCapacity) Creates an empty queue with the specified initial capacity
PriorityQueue(Comparator<? super E> comparator) Creates an empty queue with the specified comparator
PriorityQueue(Collection<? extends E> c) Creates a queue containing the elements in the specified collection

Let's see an example:

PriorityQueue<String> fruitQueue = new PriorityQueue<>();
PriorityQueue<Integer> numberQueue = new PriorityQueue<>(20);

In the first line, we're creating a queue for strings (maybe fruit names?). In the second, we're making a queue for numbers that can initially hold 20 items.

Class Methods

Now, let's look at some of the cool things you can do with a PriorityQueue:

Method Description
add(E e) Adds an element to the queue
offer(E e) Adds an element to the queue (returns false if full)
peek() Retrieves, but does not remove, the head of the queue
poll() Retrieves and removes the head of the queue
remove(Object o) Removes a single instance of the specified element
size() Returns the number of elements in the queue
clear() Removes all elements from the queue

Let's see these in action:

PriorityQueue<String> animalQueue = new PriorityQueue<>();

animalQueue.add("Dog");
animalQueue.offer("Cat");
animalQueue.add("Elephant");

System.out.println("Peek: " + animalQueue.peek()); // Prints: Peek: Cat
System.out.println("Poll: " + animalQueue.poll()); // Prints: Poll: Cat
System.out.println("Size: " + animalQueue.size()); // Prints: Size: 2

Notice how "Cat" came first? That's because PriorityQueue sorts strings alphabetically by default.

Methods Inherited

PriorityQueue also inherits methods from its parent classes. It's like getting bonus features! Some useful ones include:

  • contains(Object o): Checks if the queue contains the specified element
  • toArray(): Returns an array containing all elements in the queue
  • iterator(): Returns an iterator over the elements in the queue

Here's a quick example:

PriorityQueue<Integer> numberQueue = new PriorityQueue<>();
numberQueue.add(5);
numberQueue.add(2);
numberQueue.add(8);

System.out.println("Contains 2? " + numberQueue.contains(2)); // Prints: Contains 2? true

Object[] array = numberQueue.toArray();
System.out.println("First element: " + array[0]); // Prints: First element: 2

Adding an Item to a Priority Queue Example

Let's put it all together with a fun example. Imagine we're organizing a party, and we want to greet our guests in order of their arrival time:

import java.util.PriorityQueue;

public class PartyGreeter {
    public static void main(String[] args) {
        PriorityQueue<Guest> guestQueue = new PriorityQueue<>();

        guestQueue.add(new Guest("Alice", 18.30));
        guestQueue.add(new Guest("Bob", 18.15));
        guestQueue.add(new Guest("Charlie", 18.45));

        while (!guestQueue.isEmpty()) {
            Guest guest = guestQueue.poll();
            System.out.println("Welcome, " + guest.name + "! You arrived at " + guest.arrivalTime);
        }
    }

    static class Guest implements Comparable<Guest> {
        String name;
        double arrivalTime;

        Guest(String name, double arrivalTime) {
            this.name = name;
            this.arrivalTime = arrivalTime;
        }

        @Override
        public int compareTo(Guest other) {
            return Double.compare(this.arrivalTime, other.arrivalTime);
        }
    }
}

This program will output:

Welcome, Bob! You arrived at 18.15
Welcome, Alice! You arrived at 18.3
Welcome, Charlie! You arrived at 18.45

In this example, we created a custom Guest class and told Java how to compare guests based on their arrival time. The PriorityQueue then automatically sorted our guests for us!

And there you have it! You've just taken your first steps into the world of PriorityQueues in Java. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Who knows? Maybe you'll use a PriorityQueue to organize your next party's guest list!

Credits: Image by storyset