equals 与 hashCode
Coddy 面向 GDScript 开发者的 Java 课程的第 41 课,共 48 课。
GDScript 中的对象 == 通常用于测试对象标识;脚本可以提供显式的值比较方法,而不是重载该运算符。Java 中普通的 Object.equals 也默认比较对象标识,但值类可以同时重写 equals 和 hashCode。比较预期字段,并拒绝 null 或无关对象。相等的值必须具有相等的哈希值,而不相等的值允许发生哈希冲突。在哈希集合中,保持与相等性相关的键状态稳定。
GDScript
extends Node
class PointData:
extends RefCounted
var x: int
var y: int
func _init(px: int,py: int) -> void:
x=px
y=py
func same(other: PointData) -> bool:
return x==other.x and y==other.y
func _ready() -> void:
var a: PointData = PointData.new(1,2)
var b: PointData = PointData.new(1,2)
prints(a.same(b),a==b)
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
static class Point {final int x,y;Point(int x,int y){this.x=x;this.y=y;}public boolean equals(Object o){if(!(o instanceof Point))return false;Point p=(Point)o;return x==p.x&&y==p.y;}public int hashCode(){return Objects.hash(x,y);}}
public static void main(String[] args) {
Set<Point>s=new HashSet<>();s.add(new Point(1,2));s.add(new Point(1,2));System.out.println(s.size());
}
}移植陷阱
一致地重写 equals 和 hashCode,确保相等的值在 HashSet 和 HashMap 中能够正常使用。
使用下面可编辑的任务文件来应用这一区别。上面的示例是独立演示;此任务使用 Exercise.solve 和可见的锁定文件 Main.java 来处理输入和输出。
挑战
简单输入为 4 行整数,依次是 x1、y1、x2、y2。Coordinate 必须实现值相等,并基于两个坐标生成一致的 hashCode;对于 null 或无关类型,返回 false。返回值相等性,然后返回两个新构造的点是否为同一对象。
从 Exercise.solve(List<String> input) 返回准确的结果文本,末尾不带换行符。可见的锁定文件 Main.java 会读取所有输入行,并在打印返回文本时添加一个换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都在 Java int 的范围内。
可编辑文件:Coordinate.java、Exercise.java、Text.java。Text.java 提供可重复使用的解析和格式化辅助方法。所有文件都位于未命名包中,并会一起编译。Main.java 是唯一的入口点,不能编辑。
可见的锁定驱动程序还会在运行输入用例之前,针对独立的新对象调用所需的类 API。请实现这些 API;仅硬编码最终输出并不足够。
亲手试试
import java.io.*;
import java.util.*;
public class Main {
private static void check(boolean condition) {
if (!condition) throw new AssertionError("Required public API behavior failed");
}
public static void main(String[] args) throws Exception {
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) input.add(line);
Coordinate p=new Coordinate(3,5),q=new Coordinate(3,5);check(p.equals(q)&&q.equals(p)&&p.hashCode()==q.hashCode()&&!p.equals(null)&&!p.equals("x")&&!p.equals(new Coordinate(5,3)));Set<Coordinate> points=new HashSet<>();points.add(p);points.add(q);check(points.size()==1);
System.out.println(Exercise.solve(input));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 Java中的所有课
自己练习: Java 在线编译器