Does a PriorityQueue allow elements already within the queue to be reordered?

后端 未结 3 1982
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 19:42

I want to augment or lower the priority of items in a PriorityQueue: for example, I might be downloading a long list of images and suddenly want the thirtieth one t

3条回答
  •  死守一世寂寞
    2021-01-25 20:10

    If you look at the source code, every time you poll() on a PriorityQueue it resifts, but it always returns the item that was at the top before the sift.

    public class PQ {
    
      int priority;
    
      public PQ(int priority) {
        this.priority = priority;
      }
    
      public static void main(String[] args) {
    
        PQ one = new PQ(1);
        PQ two = new PQ(2);
        PQ three = new PQ(3);
        PQ four = new PQ(4);
        PQ five = new PQ(5);
    
        PriorityQueue q = new PriorityQueue(3, new Comparator() {
          @Override
          public int compare(PQ o1, PQ o2) {
            return o1.priority-o2.priority;
          }
        });
    
        q.add(three);
        q.add(one);
        q.add(four);
        q.add(two);
        q.add(five);
    
        //Prints;
        //PQ-1
        //PQ-2
        //PQ-3
        //PQ-4
        //PQ-5
        while (!q.isEmpty()) {
          System.out.println(q.poll());
        }
    
        q.add(three);
        q.add(one);
        q.add(four);
        q.add(two);
        q.add(five);
    
        //Change the priority after it has been queued
        four.priority = 10;
    
        //Prints;
        //PQ-1
        //PQ-2
        //PQ-3
        //PQ-5
        //PQ-10
        while (!q.isEmpty()) {
          System.out.println(q.poll());
        }
    
        //Reset the priority
        four.priority = 4;
    
        q.add(three);
        q.add(one);
        q.add(four);
        q.add(two);
        q.add(five);
    
        //Change the priority after it has been queued
        four.priority = 0;
    
        //Prints;
        //PQ-1
        //PQ-0
        //PQ-2
        //PQ-3
        //PQ-5
        while (!q.isEmpty()) {
          System.out.println(q.poll());
        }
      }
    
      public String toString() {
        return "PQ-" + priority;
      }
    
    }
    

提交回复
热议问题