英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论