gpt4 book ai didi

java - 在 Java 中使用 Map 时 containsKey 到底是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 01:23:06 25 4
gpt4 key购买 nike

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

那么即使我有正确的 key ,为什么我会得到错误?如何使用 key 检查 33 的值?

最佳答案

这里您使用字符串作为键

Map<String, Integer> map = new HashMap<>();

map.put("user1", 1);

String ia 类实现HashCodeEquals方法,因此它按预期工作。

当您使用Person时类对象作为键或任何自定义类,您应该确保覆盖 Hashcodeequals方法。

HashMap实现使用hashCode查找桶及其用途equals如果存储桶中存在多个条目。

关于java - 在 Java 中使用 Map 时 containsKey 到底是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57343069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com