MST

星途 面试题库

面试题:Java中自定义类型作为HashMap key的基本要求

在Java中,若要将自定义类型作为HashMap的key,需要满足哪些基本要求?请详细说明并举例代码实现。
37.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 基本要求
    • 重写equals方法:用于判断两个自定义类型对象在逻辑上是否相等。因为HashMap在判断键是否相等时,会调用键对象的equals方法。如果不重写,默认使用Object类的equals方法,该方法比较的是对象的内存地址,这通常不符合业务逻辑需求。
    • 重写hashCode方法HashMap通过键对象的hashCode值来确定该键值对在哈希表中的存储位置。如果两个对象根据equals方法比较相等,那么它们的hashCode值必须相等;但两个对象hashCode值相等,它们根据equals方法不一定相等。
  2. 示例代码
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方法,根据idname属性来判断两个CustomKey对象是否相等。
  • CustomKey类也重写了hashCode方法,基于idname属性生成哈希码。
  • main方法中,创建了两个逻辑上相等的CustomKey对象key1key2,并将它们作为键放入HashMap中。由于重写了equalshashCode方法,key2会覆盖key1对应的值。