Michael
Michael

Reputation: 1

Question about java priority queues

I'm trying to have a queue that can take objects of type X. Each of these object X have a variable of type int called distance. How do I make a priority queue that takes object of type X but sorts them based on each object's variable distance?

Upvotes: 0

Views: 159

Answers (3)

Mingyu
Mingyu

Reputation: 33359

You may use the following comparator:

import java.util.Comparator;

public class XComparator implements Comparator<X>
{
    @Override
    public int compare(X m, X n)
    {

        if (m.distance < n.distance)
        {
            return -1;
        }
        if (m.distance > n.distance)
        {
            return 1;
        }
        return 0;
    }
}

Here's how you would create the priority queue:

int initialCapacity = 20;
Comparator<X> comparator = new XComparator();
PriorityQueue<X> queue = new PriorityQueue<X>(initialCapacity, comparator);

Upvotes: 1

user684934
user684934

Reputation:

Homework much?

Have a look at the wiki page.

In short, you can implement a priority queue with a heap.

Upvotes: 0

Jeff Foster
Jeff Foster

Reputation: 44706

PriorityQueue provides a constructor that takes a comparator. You can use this to order the items.

Upvotes: 2

Related Questions