如果我需要使用 InfoName
作为 HashMap
的 key
,我是否需要定义我自己的 hashCode()
和 equals()
方法?我认为没有必要,因为 String name
变量足以确保 InfoName
的每个对象都不同。
public class InfoName {
enum Type {
company, product;
}
public String name;
public Type type;
public InfoName(String name, Type type) {
this.name = name;
this.type = type;
}
}
最佳答案
the String "name" variable will be enough to make sure each object of InfoName is different
如果您只想在 InfoName
中使用 name
,那么只需将 String
键入 name
为key
因为它已经覆盖了 equals()
和 hashCode()
。
或
你需要覆盖 InfoName
类中的 equals()
和 hashCode()
,否则 JVM 怎么知道你的属性/标准用于哈希和相等性检查。
关于java - 我是否需要定义自己的 hash 和 equal 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31438016/