I need to sort lists of objects with a non-static comparator that uses a value from it's outer object field.
class A {
public int x;
public int y;
public int z;
public Comparator<A> scoreComparator = new Comparator<A>() {
public compare(A o1, A o2) {
// System.out.println("this: " + this);
return (int) (x * o1.x - x * o2.x);
}
}
public A(int _x, int _y, int _z) {
x = _x;
y = _y;
z = _z;
}
}
A var_1 = new A(1, 2, 3);
A var_2 = new A(5, 6, 7);
List<A> list = getMyListFromSomewhere();
// the following will produce different ordering
Collections.sort(list, var_1.scoreComparator);
Collections.sort(list, var_2.scoreComparator);
But for some reason this does not work properly. When I uncomment the println line in the comparator, it shows that the references are to A objects, but they are different within one sort() call, therefore the value of "x" is different. What am I doing wrong here?