【问题标题】:Does Java PriorityQueue rearrange itself when I change the key of an entry?当我更改条目的键时,Java PriorityQueue 是否会重新排列?
【发布时间】:2018-06-03 23:19:15
【问题描述】:

假设我有一个优先队列

class Node{
        public int id;
        public int dist = Integer.MAX_VALUE;
        public Node(int id) { this.id = id; }
}

Queue<Node> q = new PriorityQueue<>((a, b) -> Integer.compare(a.dist, b.dist));

如果我这样做了(假设一/两个是节点对象)

Node one = new Node(1);
Node two = new Node(2);
one.dist = 1;
two.dist = 2;
q.offer(one);
q.offer(two);
two.dist = -1;

队列的行为是什么? two会在现在之前出现吗?

谢谢!

【问题讨论】:

  • @BeeOnRope,我不知道它如何更完整......
  • 为什么不直接运行代码并找出答案?
  • 不,不会。队列不知道其中项目的属性或它们的变化。您需要删除、更新、插入。
  • 您的代码会导致未定义的行为。文档明确指出您不能这样做。
  • @BoristheSpider 除非你能想出应该发生什么的规范,否则是的。

标签: java priority-queue


【解决方案1】:

Java API 的不同实现可能会有不同的行为。但是,关于 OpenJDK:不。诸如peek 之类的操作不会对集合进行重新排序:它们仅返回已排序集合中的第一个值。因此,除非您使用队列的方法,否则它无法知道顺序已更改。

事实上,即使调用add(例如)也不会求助于现有项目:它假定现有项目已排序,因为它将新项目打乱到队列中的正确位置。

参见 openJDK 实现中的source code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 2015-03-16
    • 2014-06-10
    • 1970-01-01
    • 2011-09-11
    • 2019-06-19
    相关资源
    最近更新 更多