Java Priority Queue of User-Defined Objects Example

In this source code example, you’ll learn how to create a Java Priority Queue of user-defined objects.

Since a Priority Queue needs to compare its elements and order them accordingly, the user-defined class must implement the Comparable interface, or you must provide a Comparator while creating the priority queue. Otherwise, the priority queue will throw a ClassCastException when you add new objects to it.

Priority Queue of User-Defined Objects Example

import java.util.PriorityQueue;

class Person implements Comparable<Person> {
    String name;
    int age;

    public Person(String name, int age) { = name;
        this.age = age;

    public int compareTo(Person other) {
        return this.age - other.age; // Compare based on age

    public String toString() {
        return name + ": " + age;

public class PriorityQueueUserDefined {
    public static void main(String[] args) {
        // 1. Create a priority queue of Person objects
        PriorityQueue<Person> people = new PriorityQueue<>();

        // 2. Add person objects to the priority queue
        people.add(new Person("John", 35));
        people.add(new Person("Doe", 25));
        people.add(new Person("Jane", 30));

        // 3. Poll (retrieve and remove) person objects from the priority queue based on age
        while(!people.isEmpty()) {
            System.out.println("Polling: " + people.poll());


Polling: Doe: 25
Polling: Jane: 30
Polling: John: 35


1. A Person class is defined which implements a Comparable interface to determine the order in the PriorityQueue.

2. The compareTo method is overridden to compare Person objects based on their age.

3. A PriorityQueue of Person objects is created and populated.

4. The poll method retrieves and removes the Person with the lowest age (highest priority) until the queue is empty.