【问题标题】:Why && in return and casting? [closed]为什么 && 作为回报和铸造? [关闭]
【发布时间】:2020-02-15 08:37:40
【问题描述】:

我在看核心 Java 书,相等性测试部分让我有点困惑

  1. 这个具体的返回行是什么意思,尤其是&&
  2. 当它已经知道它是否属于同一类时,为什么还需要将otherObject 转换为 Employee?
class Employee 
{
...
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null 
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal 
        if (getClass() != otherObject.getClass())
           return false;
        // now we know otherObject is a non-null Employee 
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values 
        return name.equals(other.name)
           && salary == other.salary
           && hireDay.equals(other.hireDay);
    }
}

【问题讨论】:

  • && "in" a return 的含义与其他任何可以使用的地方都一样
  • otherObject 的类型为 Object。它也可以是Cat,而不是Employee。在该方法中,您确保它实际上是Employee(之前的if)。所以现在你想比较他们的字段,比如姓名和薪水等。为此,你必须告诉 Java “嘿,这实际上是一个Employee,相信我”。否则你无法访问它,因为 Java 会试图保护你不访问猫的薪水,这是行不通的。
  • 既然要覆盖equals,就必须覆盖hashCode。
  • 某些语言(例如 Kotlin 和 Typescript)确实具有控制流类型缩小,这意味着您不需要在类型得到保证的分支中进行转换。但 Java 不这样做。
  • @kaya3 还没有,但是模式匹配很快就会来,可以把这从两步简化为一步。

标签: java casting return logical-operators


【解决方案1】:

这是一个逻辑短路和运算符。这是一种更短(更快)的写作方式

if (name.equals(other.name)) {
    if (salary == other.salary) {
        return hireDay.equals(other.hireDay);
    }
}
return false;

(注意原文不涉及分支)。至于为什么需要otherObjectEmployee 的演员表;正是因为它不知道otherObjectEmployee - 事实上,你有

public boolean equals(Object otherObject)

这意味着otherObjectObject(根据Object.equals(Object) 的要求)。你需要一个转换来告诉编译器在运行时otherObject 一个Employee(或者抛出一个类转换异常)。

如果您希望编译器在之后“知道”

// if the classes don't match, they can't be equal 
if (getClass() != otherObject.getClass())
   return false;

推断otherObjectEmployee 是安全的,很遗憾地通知您Java 不进行任何此类推断(当前)。编译器没有感知(尽管有时看起来像)。

【讨论】:

    【解决方案2】:

    && 是一种逻辑运算符,读作“AND AND”或“Logical AND”。该运算符用于执行“逻辑与”运算,即类似于数字电子中的与门的功能。

    要记住的一点是,如果第一个条件为假,则不会评估第二个条件,即它具有短路效应。广泛用于测试做出决定的几个条件。

    【讨论】:

    • 我只是把它读作“和”。
    • "AND AND" 是阅读&& 的一种非常不寻常的方式,就像阅读“U.S.A.”中的句点一样
    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多