chenzhongpu
chenzhongpu

Reputation: 6871

priority queue cannot sort automatically when its value has been changed

For example,

class App{

    int k;

    public App(int k)
    {
        this.k = k;
    }
}

Main Code here:

App one = new App(2);
App Two = new App(3);

PriorityQueue<App> p = new PriorityQueue<>(2,new Comparator<App>() {

        @Override
        public int compare(App o1, App o2) {

            if(o1.k < o2.k) return -1;
            return 1;
        }
});

p.add(two);
p.add(one);

Obviously, one is at the head of the queue. (p.peek().k is 2)

However, after:

one.k = 9; 
two.k = 8;

the one still is at the head of the queue (p.peek.k is 9)!! Priority queue cannot sort automatically when its value has been changed.

Is there a method that can sort the queue when its value is changed?

Hope someone can help.

Upvotes: 2

Views: 1401

Answers (1)

icza
icza

Reputation: 417622

PriorityQueue and other collections working with comparable elements (e.g. TreeSet) are not meant for mutable objects. They only work if the ordering of the elements does not change (either because you don't change them in that way, or they are immutable and hence cannot be mutated at all).

So what you do, you shouldn't. But if you still do, PriorityQueue does not provide a way to redo the ordering.

Your 2 options:

  • remove all elements and add them again
  • create a new PriorityQueue, add all elements and use that

On a side note, your Comparator is not even correct, it should return 0 if 2 values are equal. Try using o1.k - o2.k or Integer.compare(o1.k, o2.k).

Upvotes: 3

Related Questions