views:

540

answers:

1

Is it possible in Java to create a PriorityQueue of objects where the key that decides the priority is the member of the object?

All the examples I see on net insert an integer into the PriorityQueue and retrieve them. I'm looking for an implementation that would insert an instance of an object and is retrieved based on one of its member values, which might be an integer.

+10  A: 

Yes, PriorityQueue has a constructor that allows you to a pass a Comparator to define the order of the elements. For example, if you have the following Bar class:

public class Bar {
  private int priority;

  // getters / setters ...
}

And you want to create a priority queue that orders the elements based on the priority field (e.g., items with greater priority stay in the front of the queue), you can use the following:

Queue<Bar> queue = new PriorityQueue<Bar>(new Comparator<Bar>() {
  public int compare(Bar a1, Bar a2) {
    return a2.getPriority() - a1.getPriority(); // adapt this to your needs
  }
});

If you have more complex logic in the compare method, or if you want to reutilize the code, then I suggest you create a class, say BarComparator, that implements Comparator<Bar>.

Also, as an alternative to the above, you can make Bar implement the Comparable interface, and use the empty constructor, like so:

public class Bar implements Comparable<Bar> {
  private int priority;

  @Override
  public int compareTo(Bar b) {
    return b.getPriority() - this.priority;
  }
}

Hope it helps.

JG
when you say ordering by greater priority do you mean in the sense that a Bar with priority 3 has a greater priority then a Bar with priority 13, in the sense that Bar's that have a smaller priority value actually have a "greater priority"
Tomek
The exact opposite. A `Bar a` with a priority 20 has a greater priority than a `Bar b` with priority 18, and thus, `Bar a` stays in the front of the queue.
JG