代码之家  ›  专栏  ›  技术社区  ›  Essej

Java CompareTo方法声明,我无法将int转换为布尔值,即使两者都未使用

  •  0
  • Essej  · 技术社区  · 10 年前
    public int compareTo(Person p) {
        int res = 1;
        String personStr = p.getId();
        String thisId = this.getId();
    
        if(thisId.equals(personStr)){
            res = 0;
        }
        else if(thisId.compareTo(personStr)){
            res = -1;
        }
    
        return res;
    }
    

    我实现了一个相当简单的compareTo方法,但我没有得到错误消息。else if statemin中的条件给了我一条消息,说它不能从int转换为boolean。我明白,但问题是我在用nether。我只想比较两个简单的字符串,为什么会发生这种情况?

    3 回复  |  直到 10 年前
        1
  •  7
  •   Will    10 年前

    您应该注意的是,接口“compareTo”正在返回一个int“public int compareTo”作为符号

    if语句依赖于布尔值,但是您使用thisId。compareTo(personStr),它将返回一个整数,就像您正在创建的方法一样。

    您的第一个if语句很好-“equals”返回一个布尔值。然而,第二个函数没有,它可能会返回-1、0或1。

        2
  •  2
  •   David    10 年前

    但问题是我在用nether

    你确定吗?

    这将导致 int :

    thisId.compareTo(personStr)
    

    但你用它作为 Boolean :

    if (yourResult)
    

    if 语句需要一个布尔值,它不能只用于任何值。例如,考虑以下两者之间的区别:

    if (value == 1)
    

    这是:

    if (value)
    

    在某些语言中,你可以逃脱惩罚。一些语言将“真实性”的程度指定给所有类型,允许您在布尔表达式中使用它们。Java不是其中之一。您必须在Java中显式定义布尔逻辑:

    if(thisId.compareTo(personStr) > 0) // or whatever your logic should be
    
        3
  •  0
  •   Kai Iskratsch    10 年前

    如果你只是想比较这两个字符串,为什么不使用

    public int compareTo(Person p) {
      String personStr = p.getId();
      String thisId = this.getId();
      return thisId.compareTo(personStr);
    }
    
    推荐文章