← 中文资源

简体中文版本

手写 equals 与 hashCode 契约

在普通类上手写 equals 与 hashCode:equals 判等、Objects.hash 生成散列,两个相等的对象落在同一个桶里,HashSet 才能查到并拒绝重复添加。

阅读英文原文

实现说明

手写 equals 与 hashCode 契约以类 PointKey、Point和函数 equals、hashCode、main为骨架。

使用要点

  • 跑完文件,输出里会留下标记——contains equal point:、re-add rejected:。

常见问题

运行「手写 equals 与 hashCode 契约」会打印什么?

运行文件本身,contains equal point:、re-add rejected: 这些前缀各对应一段演示逻辑。

主要签名是 public boolean equals(Object other)

核心语句

if (!(other instanceof Point p)) return false;
if (this == other) return true;
return x == p.x && y == p.y;

代码示例

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class PointKey {

    static final class Point {
        final int x;
        final int y;

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

        // 相等的对象必须有相同 hashCode,否则 HashSet 找不回来
        @Override
        public boolean equals(Object other) {
            if (this == other) return true;
            if (!(other instanceof Point p)) return false;
            return x == p.x && y == p.y;
        }

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

    public static void main(String[] args) {
        Set<Point> visited = new HashSet<>();
        visited.add(new Point(1, 2));
        System.out.println("contains equal point: " + visited.contains(new Point(1, 2)));
        System.out.println("re-add rejected: " + !visited.add(new Point(1, 2)));
    }
}