Menu
CoddyTech

equals 与 hashCode

Coddy 面向 C# 开发者的 Java 课程的第 41 课,共 48 课。

C# 值类型和记录可以提供值相等性,类也可以实现 IEquatable,并使用匹配的 GetHashCode 行为。普通的 Java 类必须显式实现选定的值契约,或者使用合适的生成形式,例如记录。在两种语言中,作为基于哈希的集合键且相等的对象都需要有一致的哈希值。值类需要针对有意义的字段实现 equals,并提供一致的 hashCode。相等的对象必须具有相等的哈希值;不相等的对象可能发生哈希冲突。要处理 null 和无关类型。哈希集合依赖此契约,而不仅仅是可打印的文本。

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
class Point:IEquatable<Point>{private readonly int x,y;public Point(int x,int y){this.x=x;this.y=y;}public bool Equals(Point other){return other!=null&&x==other.x&&y==other.y;}public override bool Equals(object other){return Equals(other as Point);}public override int GetHashCode(){return x*31+y;}}
static void Main() {
var points=new HashSet<Point>{new Point(1,2),new Point(1,2)};Console.WriteLine(points.Count);
}
}

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());
}
}

移植陷阱

只重写相等性,却没有提供兼容的哈希码,可能会破坏哈希集合的行为。

在可编辑的任务文件中应用此比较。这些独立示例使用各自的入口点;练习 API 是 Exercise.solve,由可见且锁定的 Main.java 调用。

challenge icon

挑战

简单

输入为 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));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 Java中的所有课

自己练习: Java 在线编译器