9

我有一个要放入哈希图中的 Color 类。我想调用containsKeyhashmap 以确保对象是否已经存在于 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红色

如何做到这一点?

4

1 回答 1

15

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

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

另请阅读:

在 Java 中覆盖 equals 和 hashCode

于 2012-10-08T02:48:29.763 回答