0

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?

hammar
  • 138,522
  • 17
  • 304
  • 385
  • possible duplicate of [Java: How do I use a PriorityQueue?](http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue) – Bart Kiers Apr 15 '11 at 09:18

3 Answers3

2

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

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
1

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);
Mingyu
  • 31,751
  • 14
  • 55
  • 60
0

Homework much?

Have a look at the wiki page.

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