我有一个名为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
?
instanceof
的模式匹配 - QBrutepoint
变量的声明对于下面的代码行是必要的。请参阅JEP开始的部分“The flow scoping analysis...”。 - Michael