有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的相等对象

这是来自Head First Java(第563页)

The default behaviour of hashCode() is to generate a unique integer for each object on the heap. So if you don’t override hashCode() in a class, no two objects of that type can EVER be considered equal.

但我认为,一个简单的测试就能证明这一点

public class Song {

    private String name;

    public Song(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }


    @Override
    public boolean equals(Object obj) {
        Song objectSong = (Song) obj;
        return this.getName().equals(objectSong.getName());
    }

}

这会变成现实:

Song songA = new Song("A","B");
Song songB = new Song("A","C");

System.out.println(songA.equals(songB));

我错过什么了吗?这本书想告诉我什么


共 (1) 个答案

  1. # 1 楼答案

    The default behaviour of hashCode() is to generate a unique integer for each object on the heap. So if you don’t override hashCode() in a class, no two objects of that type can EVER be considered equal.

    你误解了。作者并不是说一个方法(即所有equalshashCode)不能为两个不同的对象返回true。他们说,如果两个对象的hashCode结果不相等,那么在语义上不应该认为两个对象是相等的。他们正在描述hashCode应该如何使用。如果你用不同的方法,你可能会得到奇怪和意想不到的结果