Yi Son
Yi Son

Reputation: 235

How to create Priority Queue that sorts based on certain attribute of class?

I have created a Node class:

public class Node {
int vertex;
double latency;
Node predecessor;}

 public double getLatency()
{
    return latency;
}

I want to create a Priority Queue that sorts the Nodes by latency from least to greatest. After research, I believe I need to override the Comparator?

PriorityQueue<Node> pqueue = new PriorityQueue<Node>(numVertices, new Comparator<Node>({
        @Override

            ???
        }
    }

I'm not too sure how to override it.

Upvotes: 2

Views: 2274

Answers (2)

iberbeu
iberbeu

Reputation: 16195

You just actually need to compare both latencies. That means overriding the method compare of the class Comparator comparing the latency of both input Node:

PriorityQueue<Node> pqueue = new PriorityQueue<Node>(numVertices, new Comparator<Node>({
    @Override
    public int compare(Node a, Node b) {
        return Integer.compare(a.getLatency(), b.getLatency());
    }
}

However this only works for Java 7, for other versions:

new Integer(a.getLatency()).compareTo(new Integer(b.getLatency()));

If you don't want to create a new Object then compare both int as usual

Upvotes: 2

Tom McCann
Tom McCann

Reputation: 36

The "???" in your example can be replaced with the following:

public int compare(Node a, Node b) {
    if (a.getLatency() < b.getLatency())
        return -1;
    else if (a.getLatency() > b.getLatency())
        return 1;
    return 0;
}

Upvotes: 1

Related Questions