PriorityQueue add Element 会改变元素,奇怪的bug
PriorityQueue add Element will change the element, weird bug
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] 谁能解释为什么会这样?提前致谢!
问题出在 compareTo 方法中:
return this.rac[2] = that.rac[2];
它总是返回后者 that.rac[2]
。应该是:
return this.rac[2] == that.rac[2];
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] 谁能解释为什么会这样?提前致谢!
问题出在 compareTo 方法中:
return this.rac[2] = that.rac[2];
它总是返回后者 that.rac[2]
。应该是:
return this.rac[2] == that.rac[2];