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

bir*_*rdy 9 java hashmap

我有一个我在hashmap中放置的Color类.我想调用containsKeyhashmap来确保该对象是否已存在于hashmap中

颜色类

public class Color {
  public String name;
  Color (String name) {this.name = name;}
  //getters setters for name 
}
Run Code Online (Sandbox Code Playgroud)

HashMap中

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
Run Code Online (Sandbox Code Playgroud)

既然c1name红色.我希望System.out返回true,因为地图中已经存在的键cname红色

怎么能实现这一目标?

kos*_*osa 15

您的自定义类Color应该覆盖equals()hashcode()实现您想要的方法.

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

另请阅读:

覆盖Java中的equals和hashCode