面试题答案
一键面试- 基本要求:
- 重写
equals
方法:用于判断两个自定义类型对象在逻辑上是否相等。因为HashMap
在判断键是否相等时,会调用键对象的equals
方法。如果不重写,默认使用Object
类的equals
方法,该方法比较的是对象的内存地址,这通常不符合业务逻辑需求。 - 重写
hashCode
方法:HashMap
通过键对象的hashCode
值来确定该键值对在哈希表中的存储位置。如果两个对象根据equals
方法比较相等,那么它们的hashCode
值必须相等;但两个对象hashCode
值相等,它们根据equals
方法不一定相等。
- 重写
- 示例代码:
import java.util.HashMap;
import java.util.Map;
class CustomKey {
private int id;
private String name;
public CustomKey(int id, String name) {
this.id = id;
this.name = name;
}
// 重写equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomKey customKey = (CustomKey) o;
return id == customKey.id && name.equals(customKey.name);
}
// 重写hashCode方法
@Override
public int hashCode() {
int result = 17;
result = 31 * result + id;
result = 31 * result + name.hashCode();
return result;
}
}
public class HashMapCustomKeyExample {
public static void main(String[] args) {
Map<CustomKey, String> hashMap = new HashMap<>();
CustomKey key1 = new CustomKey(1, "Alice");
CustomKey key2 = new CustomKey(1, "Alice");
hashMap.put(key1, "Value for Key1");
// 由于重写了equals和hashCode方法,这里会覆盖掉key1对应的值
hashMap.put(key2, "Value for Key2");
System.out.println(hashMap.get(key1));
}
}
在上述代码中:
CustomKey
类重写了equals
方法,根据id
和name
属性来判断两个CustomKey
对象是否相等。CustomKey
类也重写了hashCode
方法,基于id
和name
属性生成哈希码。- 在
main
方法中,创建了两个逻辑上相等的CustomKey
对象key1
和key2
,并将它们作为键放入HashMap
中。由于重写了equals
和hashCode
方法,key2
会覆盖key1
对应的值。