HashMap为何在相同key、相等对象时替换旧值?面试问题解析
HashMap存相同Key+相等Value?我面试踩过这个坑,给你说清楚!
嘿,这个问题我之前面试也被问到过,当时的回答和你一样,以为不会替换也不会加重复元素,结果回去写代码验证脸都疼了——旧对象真的会被完全替换掉!
先上一段验证代码,一看就懂:
import java.util.HashMap; import java.util.Objects; public class HashMapValueTest { public static void main(String[] args) { HashMap<String, Person> personMap = new HashMap<>(); Person p1 = new Person("Bob", 30); Person p2 = new Person("Bob", 30); // p1和p2的equals返回true,hashCode也一致 personMap.put("profile", p1); System.out.println("第一次存入后:" + personMap.get("profile")); // 输出p1的信息 personMap.put("profile", p2); System.out.println("第二次存入后:" + personMap.get("profile")); // 输出p2的信息,p1被替换了 } static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } }
那为啥会这样?核心原因在于HashMap的设计逻辑是围绕Key来构建的:
- 当调用
put()方法时,HashMap只关心Key是否重复——它会通过Key的hashCode()找桶,再用equals()判断桶里有没有相同的Key - 只要找到相同的Key,不管对应的Value是不是相等,都会直接用新Value覆盖旧Value,这是HashMap“一个Key对应唯一Value”的核心规则
- Value的相等性完全不在HashMap的校验逻辑里,它只是Key绑定的“附加数据”,HashMap不会为了Value去做额外判断
你之前的误解可能是把HashMap和HashSet搞混了——HashSet底层是用HashMap实现的,它把元素当作Key存,所以会判断元素的相等性,但HashMap的Value是不做这个校验的。
内容的提问来源于stack exchange,提问作者Artem
相关产品推荐
相关产品推荐

