使用自定义类在 hashmap 上调用 containsKey [英] calling containsKey on a hashmap with custom class

查看:30
本文介绍了使用自定义类在 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

因为 c1name 红色.我希望 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆