How to implement a priority queue using the field of a class in java

740 views Asked by At

I have a java class called MeterReading with two fields String MeterName and int MeterLevel.

Now, if the MeterLevel is between 0 and 3, that is Low, when between 3 and 6, Medium and from 6 above is High. How would I pass in that class MeterReading to a priority queue? Is this possible?

1

There are 1 answers

3
Davide Lorenzo MARINO On BEST ANSWER

You have to implements Comparable interface of your class. The trick is adding a method to get the levelClass (LOW, MEDIUM, HIGH) that is used in the compareTo method.

public class MeterReading implements Comparable {
    public static final int LOW = 0;
    public static final int MEDIUM = 1;
    public static final int HIGH = 2;

    private String name;
    private double level;

    ... // Constructor, getter setter and business logic methods

    public int getLevelClass() {
        if (level < 3) {
            return LOW;
        } else if (level < 6) {
            return MEDIUM;
        } else {
            return HIGH;
        }
    }

    public int compareTo(MeterReading m2) {
        return getLevelClass() - m2.getLevelClass();
    }
}

The implementation of compareTo can be also the following if you need the opposite priority.

public int compareTo(MeterReading m2) {
    return m2.getLevelClass() - getLevelClass();
}

To add a MeterReading to a PriorityQueue only add it

MeterReading mr = ....;
PriorityQueue pq = ....;
....
pq.add(mr);