简体   繁体   English

我进行轮询时PriorityQueue如何工作?

[英]How PriorityQueue work when I do poll?

I have a predefined class named Pair with a key and a value. 我有一个名为Pair的预定义类,其中包含一个键和一个值。 I store them in PriorityQueue based on the natural order of value of each Pair. 我根据每个对的自然值将它们存储在PriorityQueue中。 When I change value of one of the Pair and then dequeue, what I expect did not happen. 当我更改对中的一个的值然后出队时,我所期望的没有发生。 The test code is below. 测试代码如下。 Please help. 请帮忙。 I feel confused! 我感到困惑!

import java.util.*;
public class Test {
  static class Pair {
      int key;
      int value;
      Pair (int key, int value) {
        this.key = key;
        this.value = value;
      }
  }
  public static void main(String[] args) {
      PriorityQueue<Pair> pq = new PriorityQueue<Pair>(3, new Comparator<Pair>() {
        @Override
        public int compare(Pair p1, Pair p2) {
            return p1.value - p2.value;
        }
    });
    Pair p1 = new Pair(1, 31);
    Pair p2 = new Pair(2, 32);
    Pair p3 = new Pair(3, 33);
    pq.offer(p1);
    pq.offer(p2);
    pq.offer(p3);
    p2.value = 31;
    p1.value = 32;
    Pair p0 = pq.poll(); // It shows the reference p0 is p1 not expected p2. 
                        // And what remain in pq are p2 with 31 and p3 with 33
  }
}

I know that PriorityQueue will sort the item when polling. 我知道PriorityQueue将在轮询时对项目进行排序。 It seems like the PriorityQueue in my example didn't work. 在我的示例中,PriorityQueue似乎不起作用。

When you have any data structure such as a Hash Map/Set, TreeMap/Set or a sorted queue like PriorityQueue, if you mutate one of the elements (in particular a field used for hashCode/equals/compareTo depending on what methods(s) are used), the data structure doesn't know to re-arrange itself, instead what you are doing is corrupting the data structure so it won't work as expected. 当您具有任何数据结构(例如哈希映射/集合,TreeMap /集合或诸如PriorityQueue之类的已排序队列)时,如果您突变其中一个元素(特别是用于hashCode / equals / compareTo的字段,具体取决于哪种方法)使用),则数据结构不知道如何重新安排自身,而是您正在做的是破坏数据结构,因此它无法按预期工作。

In short, you can't mutate the key fields of an object in a data structure and expect it to behave in a reliable manner. 简而言之,您不能更改对象在数据结构中的关键字段并期望它以可靠的方式运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM