I have an object, Test
, that has two properties, double x
and double y
. I want to add these objects to a SortedSet
, keeping the set sorted in ASC order on x of Test
. If two instances of Test
have the same x values, I want them to be sorted within the set by their y values.
I thought the following would do the trick:
private SortedSet<Test> tests = new TreeSet<Test>(new Comparator<Test>() {
@Override
public int compare(Test o1, Test o2) {
if (o1.getXpos() < o2.getXpos()) {
return -1;
}
if (o1.getXpos() > o2.getXpos()) {
return 1;
}
if (o1.getXpos() == o2.getXpos()) {
if (o1.getYpos() < o2.getYpos()) {
return -1;
}
if (o1.getYpos() > o2.getYpos()) {
return 1;
}
if (o1.getYpos() == o2.getYpos()) {
return 0;
}
}
return 0;
}
});
Instead this orders the actual x and y values; i.e.
testA: x=200, y=200,
testB: x=200, y=400
After inserting into tests
:
testA: x=200, y=200,
testB: x=400, y=200
Instead of the instances within tests
.