如何覆盖compareTo方法

Red*_*ion 0 java

这是我的compareTo方法,但我仍然得到"缺少返回语句"警告.谁能告诉我我的代码有什么问题?

    public int compareTo(Flows other) {
    if(this.srcAddr.equals(other.srcAddr)){
        if(this.dstAddr.equals(other.dstAddr)){
                 if(this.srcPort.equals(other.srcPort)){
                     if(this.dstPort.equals(other.dstPort)){
                         if(this.protocol.equals(other.protocol)){
                             return 0;
                         }
                     }
                 }
         }
 }
}
Run Code Online (Sandbox Code Playgroud)

man*_*war 5

两件事情:

  • 您将获得"缺少返回语句",因为存在没有返回值的执行路径.例如,当第一个if语句计算为false时.

  • 你打破了compareTo()合约.对于以下调用:a.compareTo(b),结果为:0如果a等于b,<0如果a小于b,则> 0如果a大于b.看来你正在使用compareTo()检查是否相等,在这种情况下,正确的方法是覆盖equals()方法.