java - PriorityQueue添加元素会改变元素,奇怪的bug

标签 java addition priority-queue

public class Main {    
public static class EE implements Comparable<EE> {
        int x;
        int[] rac;
        public  EE(int x, int[] rac) {
            this.x = x;
            this.rac = rac;
        }

        public int compareTo(EE that) {
            if (this.x != that.x) return this.x - that.x;
            else return this.rac[2] = that.rac[2];
        }
    }

public static void main(String[] args) {
        int [][] ary = {
                {1,1,3,3},

                {1,3,2,4},
                {2,3,3,4}};
        PriorityQueue<EE> pq = new PriorityQueue<EE>();
        for (int[] rec : ary) {
            EE e1 = new EE(rec[0], rec);
            EE e2 = new EE(rec[2], rec);
            pq.add(e1);
            pq.add(e2);
        }
    }

我正在运行的这段代码,一切都很好,但是当进入第二个for循环时,rec最初是[1,3,2,4],当调用pq.add(e1)时,rec的值将变成 [1, 3, 3, 4] 任何人都可以解释为什么会发生这种情况?预先感谢您!

最佳答案

问题在 comapreTo 方法中:

return this.rac[2] = that.rac[2];

它总是返回后者that.rac[2]。应该是:

return this.rac[2] == that.rac[2];

关于java - PriorityQueue添加元素会改变元素,奇怪的bug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39285944/

相关文章:

java - 简单的 scala 程序给出错误 : java. lang.InknownClassChangeError

java - Scanner(new File) 和 Scanner(new FileInputStream) 有什么区别?

java比较逗号分隔的字符串

python - 二进制加法时如何进位?

java - ArrayList.add 方法不起作用

algorithm - 设置优先队列值以优化找到 'gift' 的概率

c++ - 在O(1)中用minValue和maxValue实现MinMax PriorityQueue

java - 有没有一个库可以通过 AJAX/javascript 艰难地进行?

javascript - 为什么在 Javascript 中添加两位小数会产生错误的结果?

java - 将程序转换为使用对象而不是数字