Keeping a SortedSet of objects based on a property
문제
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
.
해결책
your comparator is correct. you've got bigger problems, though, if adding your Test objects to the set changes their member variables, e.g. "testB: x=400, y=200" -> "testB: x=200, y=400". I would guess your problem lies in code you have not included (maybe a botched constructor?).
다른 팁
Have you tried with more than two elements? More than once I've simply sorted things backwards without realizing it until later.
My guess is that comparing the double
s for exact equality using ==
is potentially the issue. See What's wrong with using == to compare floats in Java?