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];