9

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?

birdy
  • 9,286
  • 24
  • 107
  • 171

1 Answers1

15

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

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167