繁体   English   中英

如何重写compareTo方法

[英]how to override compareTo method

这是我的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;
                         }
                     }
                 }
         }
 }
}

两件事情:

  • 您会得到“缺少的返回语句”,因为存在执行路径,其中不返回任何值。 例如,当第一个if语句计算为false时。

  • 您正在违反compareTo()合同。 对于以下调用:a.compareTo(b),结果为:如果a等于b,则返回0;如果a小于b,则返回<0;如果a大于b,则返回> 0。 似乎您正在使用compareTo()检查是否相等,在这种情况下,正确的方法将覆盖equals()方法。

这看起来像一个equals方法。 如果只是要比较两者是否相同,我会做类似的事情

return srcAddr.equals(other.srcAddr) &&
       dstAddr.equals(other.dstAddr) &&
       srcPort.equals(other.srcPort) &&
       dstPort.equals(other.dstPort) &&
       protocol.equals(other.protocol);

如果这不是故意的 ,那么您可能违反了compareTo的约定,因为您的方法似乎不符合传递性要求 Comparable的文档中:

实现者还必须确保该关系是可传递的

这是因为您的代码中compareTo可能不返回任何内容! 考虑一下所有这些if语句是否失败,那么它将到达方法的末尾并且没有返回任何内容。 您需要进一步的回报:

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;
                  }
              }
          }
      }
  }
  return 1;

}

另外,您没有进行完整的比较。 如果它们相等,则需要返回0;如果差小于则返回0,如果大于则返回0。 看来您最好使用压倒一切!

也许像这样:

public boolean equals(Flows other) {
    return (this.srcAddr.equals(other.srcAddr) && this.dstAddr.equals(other.dstAddr) && this.srcPort.equals(other.srcPort) && this.dstPort.equals(other.dstPort) && this.protocol.equals(other.protocol));

只需在函数末尾添加“ return 1”(或其他任何东西),它就可以解决问题。

这将编译并运行,但是其余合同呢? 小于和大于哪里?

public int compareTo(Flows other) {

    int value = 0;

    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)){
                             value = 0;
                         }
                     }
                 }
         }

    return value;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM