tags:

views:

72

answers:

2

I want to sort objects based on Boolean values and I want to sort true values before false values.

Which of these implementations of compareTo is more readable?

Using -1 to change default behavior

public class Example implements Comparable<Example>{

  Boolean isOk;

  public int compareTo(Example o) {
      return -1 * this.isOk.compareTo(o.isOk);
  }

}

or swap sides of Boolean#compareTo method?

public class ExampleTwo implements Comparable<ExampleTwo>{

  Boolean isOk;

  public int compareTo(ExampleTwo o) {
      return o.isOk.compareTo(this.isOk);
  }

}
+1  A: 

The first form is simply wrong - because if compareTo returns Integer.MIN_VALUE, it will try to negate that - and result in Integer.MIN_VALUE again.

The easiest way to fix that is just to use the code from the second snippet.

On the other hand:

  • Both could fail if isOk is null
  • If you're really only using Booleans, a simple truth table may be simpler
  • It's possible that Boolean.compareTo will never return Integer.MIN_VALUE. I wouldn't rely on that though.
Jon Skeet
I agree with the answer but would like to point out #2 could also fail if o is null, and (though I agree #1 is not ideal) the Integer.MIN_VALUE issue could be fixed with a call to Math.signum.
M. Jessup
+2  A: 

I'd use the Ordering class from Guava (formerly Google Collections), it implements Comparator, so it can be used as a drop-in replacement:

Ordering<Object> reverseOrdering = Ordering.natural().reverse();
Joachim Sauer
+1 - when in doubt, consult Guava :)
Jon Skeet