0

I need to store objects in a heap/priority queue. However, the objects may change so that their ordering changes, so fixUp or fixDown may need to be called on them. These methods are private and Java PriorityQueue wont let me do this. My options are:

  1. use java PriorityQueue and remove and reinsert the object. Seems pretty inefficient, double the work.

  2. Implement my own priority queue and maintain code that duplicates functionality in the Java standard library.

Which would be preferred method/best practice for doing this ? This sort of operations are needed to implement many graph algorithms eg. A*, so it is surprising Java does not let you do that.

Sid Datta
  • 1,110
  • 2
  • 13
  • 29
  • possible duplicate of [Updating Java PriorityQueue when its elements change priority](http://stackoverflow.com/questions/1871253/updating-java-priorityqueue-when-its-elements-change-priority) – Raedwald Mar 20 '15 at 12:52

2 Answers2

0

Seems pretty inefficient, double the work.

But still O(lg n) with any half-decent priority queue implementation. Have to tried this and measured it? I'd only start implementing my own PQ if the one in the library is really too slow. But if you do go that way, why not fork the one in OpenJDK and "publicize" some of its methods?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Am I allowed legally to just copy an OpenJDK file and start changing it ? The best method will probably be extending PriorityQueue, but fixedUp and down are private. – Sid Datta Aug 08 '11 at 22:48
0

I would advise against "reinventing the wheel" and writing your own priority queue implementation.

If you need to make adjustments to the priority, you could use a queue of wrappers that manages the delta, something like this (assuming you can get the priority from thing):

class Wrapper implements Comparable<Wrapper> {

    private final Thing thing;
    private int delta;

    public Wrapper (Thing thing) {
        this.thing = thing;
    }

    public void adjustRank(int deltaChange) {
        delta += deltaChange;
    }

    public int compareTo(Wrapper w) {
        return thing.getRank() + delta - w.thing.getRank() - w.delta;
    }
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722