Which use of the compareTo method is more clear?

I want to sort objects based on booleans, and I want to sort true values ​​before false values.

Which of these compareTo implementations is more readable?

Using -1 to change the 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 the Boolean # compareTo method?

public class ExampleTwo implements Comparable<ExampleTwo>{

  Boolean isOk;

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

}
+3
source share
2 answers

The first form is simply incorrect, because if it compareToreturns Integer.MIN_VALUE, it will try to nullify it - and again result in Integer.MIN_VALUE.

The easiest way to fix this is to simply use the code from the second snippet.

On the other hand:

  • Both can fail if isOknull
  • Booleans,
  • , Boolean.compareTo Integer.MIN_VALUE. .
+4

Ordering Guava ( Google), Comparator, :

Ordering<Object> reverseOrdering = Ordering.natural().reverse();
+3

Source: https://habr.com/ru/post/1750993/


All Articles