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

查看:142
本文介绍了使用自定义类在散列表上调用containsKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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()方法。



另请阅读:

在Java中重写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屋!

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