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/