【问题标题】:Does changing hashCode() work if I use a string as a key to the object?如果我使用字符串作为对象的键,更改 hashCode() 是否有效?
【发布时间】:2021-06-18 16:12:19
【问题描述】:

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

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

    public boolean equals {...}

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

我主要存储这些对象的地图,如下所示:

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 类中定义的 hashCode() 函数吗?

【问题讨论】:

  • 不是你问的那样:地图的键不是Person,而是String
  • @DaveNewton 正是我想知道的,谢谢

标签: java hashcode


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在你的问题地图中

      Map map = new HashMap();

      您使用的键是 String,而 Person 对象是 Map 中的值。在 Map 中输入值时,将考虑键的 equals 和 hashcode 方法。因此,在您的场景中,它将是 String 类。在您的示例中,无法使用 Person 类的 equals 和 hashcode 方法。

      如果您想使用 Person 类的 hashcode 和 equals 方法,同时将值放入 M​​ap 中,您必须将 Person 保留为 Map 中的键。例如:

      Map[这仅用于表示目的]

      【讨论】:

      • 这正是我想知道的,谢谢。
      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2021-11-02
      • 2012-12-22
      • 1970-01-01
      • 2015-08-29
      相关资源
      最近更新 更多