【发布时间】:2019-08-04 00:55:50
【问题描述】:
containsKey 是如何真正起作用的?我知道如果我这样做:
Map<String, Integer> map = new HashMap<>();
map.put("user1", 1);
map.put("user2", 2);
map.put("user3", 3);
System.out.println(map.containsKey("user1")); // true
containsKey 返回 true
但如果我这样做:
Map<Person, Integer> table = new HashMap<>();
table.put(new Person("Steve"), 33);
table.put(new Person("Mark"), 29);
System.out.println(table.containsKey(new Person("Steve"))); // false
那么为什么即使我有正确的密钥,我也会得到 false?如何使用其键检查 33 的值?
【问题讨论】:
-
因为您的
Person类没有(正确)实现hashCode()和equals()。 -
因为你还没有在你的类上实现
equals(),所以Java只能检查这两个对象是否引用了相同的内存。这解释了平等在 Java 中的工作原理stackoverflow.com/questions/7520432/…
标签: java