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
基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
