在重写的equals函数中,“o instanceof Point point”的含义。

huangapple go评论67阅读模式
英文:

the meaning of "o instanceof Point point" in overrided equals function

问题

我有一个Point类,代码如下:
public class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point point)) return false;
        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}
equals函数由IntelliJ生成,也可以接受Point的子类作为参数。但我不理解 `if (!(o instanceof Point point))` 的含义。为什么在 `Point` 后面有 `point`,并且在equals函数中如何定义 `point`?
英文:

I have Point class as the following code:

public class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point point)) return false;
        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

The equals function is generated by IntelliJ, which can also accept a subclass of Point as a parameter. But I don't understand the meaning of if (!(o instanceof Point point)). Why is there point after Point, and how is point defined in the equals function?

答案1

得分: 4

这被称为“用于 instanceof 的模式匹配”。

我将假设你知道以前的语法,即

if (!(o instanceof Point)) return;

Point point = (Point)o;

return x == point.x && y == point.y;

从 Java 16 开始,有一种新的语法,据说更为简洁。

if (!(o instanceof Point point)) return;

return x == point.x && y == point.y;

你可以在 instanceof 语句内声明变量,而不是进行强制类型转换和创建局部变量。

JEP 394 中描述了模式变量的作用范围,被称为“流程作用域”,可能有点不直观。instanceof 操作符的模式匹配有更多示例。

英文:

This is called "Pattern matching for instanceof".

I am going to assume you know the previous syntax which would be.

if( !(o instanceof Point) ) return;

Point point = (Point)o;

return x == point.x && y == point.y;

As of java 16 there is a new syntax that is supposed to be a bit more concise.

if( !(o instanceof Point point) ) return;

return x == point.x && y == point.y;

Instead of casting and creating a local variable, you can declare the variable within the instanceof statement.

The scope of the pattern variable is described as "flow scoping" in JEP 394 which can be a bit non-intuitive. Pattern Matching for instanceof has more examples.

huangapple
  • 本文由 发表于 2023年4月19日 18:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定