Search code examples
javareturn-valuecomparablecompareto

Negative and positive return values of compare and compareTo


I read that the rule for the return value of these methods is that for obj1.compareTo(obj2) for example, if obj2 is under obj1 in the hierarchy, the return value is negative and if it's on top of obj1, then it's positive (and if it's equal then it's 0). However, in my class I saw examples where Math.signum was used in order to get -1 (for negative) and 1 (for positive) in the compareTo method.

Is there any reason for that?


EDIT:

Here is the code I meant:

Comparator comp = new Comparator() {
   public int compare(Object obj1, Object obj2) {
       Book book1 = (Book) obj1;
       Book book2 = (Book) obj2;

       int order = book1.getAuthor().compareTo(book2.getAuthor());
       if (order  == 0) {
          order = (int) Math.signum(book1.getPrice() - book2.getPrice());
       }
   return order;
};

Solution

  • Is there any reason for using Math.signum

    Yes there is.

    order = (int) Math.signum(book1.getPrice() - book2.getPrice());
    

    Suppose you have replace the above line with this

    order = (int)(book1.getPrice() - book2.getPrice());
    

    Now let us assume

    book1.getPrice() returns 10.50 
    book2.getPrice() returns  10.40
    

    If you do not use signum you will never have any compile time or run time error but value of order will be 0. This implies that book1 is equals to book2 which is logically false.

    But if you use signum value of order will be 1 which implies book1 > book2.

    But it must be mentioned that you should never make any assumption about compare function returning value between 1 and -1. You can read official document for comparator http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html.