PriorityQueue add Element会改变元素,怪异的bug

时间:2016-09-02 06:46:53

标签: java add 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],任何人都可以解释为什么会发生这种情况?提前谢谢!

1 个答案:

答案 0 :(得分:1)

preoblem在comapreTo方法中:

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

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

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