在具有自定义类的hashmap上调用containsKey

我有一个我正在放入hashmap的Color类。 我想在hashmap上调用containsKey以确保该对象是否已存在于hashmap中

颜色类

 public class Color { public String name; Color (String name) {this.name = name;} //getters setters for name } 

HashMap中

 HashMap<Color, List> m = new HashMap<Color, List>(); Color c = new Color("red"); m.put(c, new ArrayList()); 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红色

怎么能实现这一目标?

您的自定义类Color应该重写equals()hashcode()方法以实现您想要的。

当您使用自定义对象作为collections键并希望使用对象进行查找时 ,您应该正确地覆盖equals()hashcode()方法。

另请阅读:

在Java中覆盖equals和hashCode