如果我使用字符串作为对象的键,更改 hashCode() 是否有效?

Does changing hashCode() work if I use a string as a key to the object?

我一直在阅读 java 中有关更改 hashCode() 函数的内容。
我不太明白一件事: 如果我有一个 class Person,并将 HashMap 存储在 class 中,例如:
Map<String, Person> map = new HashMap<>(); 定义的 hashCode() 函数有什么作用吗? 只是据我了解,它会使用 String 的 hashCode,而不是 Person 的 HashCode() 对吗?
所以如果我有这个 class

public class Person {
    private int age;
    private String name;

    public boolean equals {...}

    public int hashCode() {
        return Objects.hash(age, name);
    }
}

在 main 上,我存储了这些对象的地图,如下所示:

public class Main {
    public static void main (String [] arg) {
        Map <String, Person> pers = new HashMap<>();
        Person p = new Person("Peter", 21); //Imagine I have this constructor
        pers.put(p.getName(), p);
    }
}

这会使用 Person class 中定义的 hashCode() 函数吗?

Hashcode 函数出现在要用作 hashmap 中的键的对象的图片中。在您给出的示例中,将使用 String class 哈希码功能。 Person class hashcode 用作 hashmap 中的键时会出现在画面中。

hashCode 用于地图的 key,而不是它的 value。在这种情况下,键是 String,因此不会调用 PersonhashCode,这是值。

在你的问题地图中

Map<String, Person> map = new HashMap<>();

您使用的键是 String 并且 Person 对象是您地图中的值。当您在 Map 中放置一个值时,将考虑键的 equals 和 hashcode 方法。所以在你的场景中它将是 String class。在您的示例中无法使用 Person class 的 equals 和 hashcode 方法。

如果您想在将值放入地图时使用 Person class 的哈希码和 equals 方法,则必须将 Person 保留为地图中的键。例如:

Map<Person,SOME_CLASS>[this is only for representational purpose]