Code Farmer Code Farmer - 3 months ago 16
Java Question

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);
}
}


This piece of code I'm running, everything is fine but when the second for loop is entered, rec is [1, 3, 2, 4] initially, when pq.add(e1) get called, value of rec will become [1, 3, 3, 4] anyone can explain why this happens? Thank you in advance!

Answer

The preoblem is in comapreTo method:

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

It's returning always the latter that.rac[2]. It should be:

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