Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling containsKey on a hashmap with custom class

Tags:

java

hashmap

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?

like image 250
birdy Avatar asked Oct 08 '12 02:10

birdy


1 Answers

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

like image 190
kosa Avatar answered Oct 28 '22 07:10

kosa