calling containsKey on a hashmap with custom class(使用自定义类在 hashmap 上调用 containsKey)
问题描述
我有一个 Color 类,我将其放入 hashmap 中.我想在 hashmap 上调用 containsKey
以确保对象是否已经存在于 hashmap 中
I have a Color class that I'm putting in the hashmap. I'd like to call containsKey
on the hashmap to ensure whether the object is already present in the hashmap
颜色类
public class Color {
public String name;
Color (String name) {this.name = name;}
//getters setters for name
}
哈希映射
HashMap<Color, List<String>> m = new HashMap<Color, List<String>>();
Color c = new Color("red");
m.put(c, new ArrayList<String>());
Color c1 = new Color("red");
System.out.println(m.containsKey(c1)); //I'd like to return this as true
因为 c1
有 name
红色.我希望 System.out
返回 true,因为地图中已经存在的键 c
具有 name
红色
Since c1
has name
red. I'd like the System.out
to return true because the key already present in the map, c
, has name
red
如何实现?
推荐答案
你的自定义类 Color
应该覆盖 equals()
和 hashcode()
实现你想要的方法.
Your custom class Color
should override equals()
and hashcode()
methods to achieve what you want.
当您使用自定义对象作为 collections
的键并希望使用对象进行 查找 时,您应该正确覆盖 equals()
和 hashcode()
方法.
When you are using custom objects as keys for collections
and would like to do lookup using object, then you should properly override equals()
and hashcode()
methods.
另请阅读:
在 Java 中覆盖 equals 和 hashCode
这篇关于使用自定义类在 hashmap 上调用 containsKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用自定义类在 hashmap 上调用 containsKey


- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01