使用自定义类在散列表上调用containsKey [英] calling containsKey on a hashmap with custom class
问题描述
我有一个Color类,我把它放在hashmap中。我想在散列图上调用 containsKey
来确保对象是否已经存在于散列表中
Color class
public class Color {
public String name;
颜色(字符串名称){this.name = name;}
// getters setters for name
}
HashMap
HashMap< Color,List< String>> m = new HashMap< Color,List< String>>();
颜色c =新颜色(红色);
m.put(c,new ArrayList< String>());
颜色c1 =新颜色(红色);
System.out.println(m.containsKey(c1)); //我想将它返回为真
由于 c1
具有
名称
红色。我希望 System.out
返回true,因为映射中已存在的键 c
具有 name
red
这怎么能实现?
Color
应该覆盖 equals()
和<$ c $使用自定义对象作为集合的关键字。 使用自定义对象作为集合的关键字
并希望使用object 进行查找,那么您应该正确地覆盖 equals()
和 hashcode()
方法。
另请阅读:
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
Color class
public class Color {
public String name;
Color (String name) {this.name = name;}
//getters setters for name
}
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
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
How can this be achieved?
解决方案 Your custom class Color
should override equals()
and hashcode()
methods to achieve what you want.
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.
Also read:
Overriding equals and hashCode in Java
这篇关于使用自定义类在散列表上调用containsKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!