0

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
wulfgarpro
  • 6,666
  • 12
  • 69
  • 110
  • 1
    http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/CompareToBuilder.html may simplify your comparison logic. – hoipolloi Mar 21 '12 at 00:56
  • Can you post the code for `Test.equals`? BTW, the test `if (o1.getXpos() == o2.getXpos())` is implied because the two `x` values are neither `<` nor `>`, assuming they're real numbers. – David Harkness Mar 21 '12 at 00:58

3 Answers3

3

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?).

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
0

Have you tried with more than two elements? More than once I've simply sorted things backwards without realizing it until later.

Argyle
  • 3,324
  • 25
  • 44
0

My guess is that comparing the doubles for exact equality using == is potentially the issue. See What's wrong with using == to compare floats in Java?

Community
  • 1
  • 1
Paul Blessing
  • 3,815
  • 2
  • 24
  • 25