Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - modified compareTo method says it needs to return an int, but it should be returning one

Tags:

java

compareto

I'm learning basic Java right now and have a problem with my code that I can't figure out. It's basically what the title says. My Java compiler is telling me that there's an error with my custom compareTo method, saying that it needs to return an int. The problem is, as far as I can tell, it IS returning an int. Yet it's still giving me an error. Could someone please point out in my code what's wrong? And also I have already implemented Comparable in my class. Here's my method:

public int compareTo(Homework other) {
    if (getDaysLate() < other.getDaysLate()) {
        return -1;
    } else if ((dateSubmitted == other.dateSubmitted)
            && (files.compareTo(other.files) == -1)) {
        return -1;
    } else if ((dateSubmitted == other.dateSubmitted)
            && (files == other.files)) {
        if (name.compareTo(other.name) == -1) {
            return -1;
        } else if (name.compareTo(other.name) == 1) {
            return 1;
        } else if (name.compareTo(other.name) == 0) {
            return 0;
        }
    } else {
        return 0;
    }
}
like image 651
user2147308 Avatar asked Mar 08 '13 06:03

user2147308


2 Answers

There is a path in the third else that does't return anything.

 else if ((dateSubmitted == other.dateSubmitted) && (files == other.files)) {
    if (name.compareTo(other.name) == -1) {
      return -1;
    }
    else if (name.compareTo(other.name) == 1) {
      return 1;
    }
    else if (name.compareTo(other.name) == 0) {
      return 0;
    } else return ...
}

BTW, I'm not sure if I'm following the logic of your implementation, since it seems that you are returning 0 if dateSubmitted != other.dateSubmitted. compareTo should also be anti-symetric (i.e. sgn(x.compareTo(y)) == -sgn(y.compareTo(x))), but your implementation is not.

like image 187
Javier Avatar answered Oct 12 '22 22:10

Javier


How can you be sure (with all these if and else) that you are always returning an int? It does not seem so obvious to me and aparently the compiler agrees with me too.

One way to solve this (probably not the best one) is to add a return -1; //or whatever value at the end of your function.

like image 28
Burkhard Avatar answered Oct 12 '22 23:10

Burkhard