1

Basically I have a priorityqueue that has a custom comparator which takes into account values that might be changed without touching the queue itself. So I want the queue to recheck itself and rearange the elements.How would I go about doing that?

a example of what I mean:

public NewClass() {

    PriorityQueue pq = new PriorityQueue(11,new CompareInts());
    CompareInts o1 = new CompareInts();
    CompareInts o2 = new CompareInts();
    o2.state = 1;
    pq.add(o1);
    pq.add(o2);

    o1.state = 3;
    //if o1 was added to the queue here, it'd be removed first
    System.out.println(pq.remove());//outputs 1
    System.out.println(pq.remove());//outputs 3




}

class CompareInts implements Comparator<CompareInts>
{
    public int state;

    public CompareInts() {
        state=0;
    }        
    @Override
    public int compare(CompareInts o1, CompareInts o2) {
        return o2.state-o1.state;
    }

    @Override
    public String toString() {
        return String.valueOf(state);
    }

}

EDIT: by the way, I understand adding an empty object and removing it would do the trick, but I'd prefer it be as optimal as possible

jonas rudzionis
  • 115
  • 2
  • 8
  • Maybe this could help you? http://stackoverflow.com/questions/1871253/updating-java-priorityqueue-when-its-elements-change-priority – divandc Nov 21 '15 at 21:25
  • 1
    Nothing built into Java will let you do this. You will have to write your own implementation. (And even then, most priority queues only support decreasing the key.) – Louis Wasserman Nov 21 '15 at 21:30
  • @divandc I've searched through the threads I found for this before posting, didn't really help, hoped something new came out to let people deal with this, sadly seems not :/ – jonas rudzionis Nov 21 '15 at 21:35
  • @LouisWasserman I've a question, can't I just make a 'custom' priority queue, with an accessible heapify method(which PriorityQueue has, only private) and use that to re-sort the queue? By custom I meant just copy everything from PriorityQueue and make the heapify public. – jonas rudzionis Nov 21 '15 at 22:00
  • 1
    You could, but that won't necessarily be any cheaper than just using a basic `List` and re-searching the entire list for the minimum element every time you do a query. – Louis Wasserman Nov 21 '15 at 22:03
  • @LouisWasserman Got it, thanks for the help! – jonas rudzionis Nov 21 '15 at 22:12

0 Answers0