Code Farmer Code Farmer - 1 year ago 90
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 = {

PriorityQueue<EE> pq = new PriorityQueue<EE>();
for (int[] rec : ary) {
EE e1 = new EE(rec[0], rec);
EE e2 = new EE(rec[2], rec);

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 Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download