equals 与 hashCode
Coddy 面向 C 开发者的 Java 课程的第 41 课,共 48 课。
C 结构体不支持通用的 == 比较;需要根据字段显式定义相等性。memcmp 可能会检查填充字节,不能可靠地替代语义上的相等性。Java 类应同时重写 equals 和 hashCode:相等的对象必须具有相同的哈希码,但不相等的对象也可能发生哈希冲突。对象作为哈希键时,应保持与相等性相关的状态稳定。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
struct Point {int x,y;};
static bool point_equal(const struct Point *a,const struct Point *b) { return a->x==b->x && a->y==b->y; }
int main(void) {
struct Point a={1,2},b={1,2}; puts(point_equal(&a,&b)?"true":"false");
return 0;
}
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());
}
}
这些示例分别展示语言行为,使用的值可能不同。请分别跟踪每个示例的执行过程,不要假设它们的预期输出相同。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));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Java中的所有课
自己练习: Java 在线编译器