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
Colorshould overrideequals()andhashcode()methods to achieve what you want.When you are using custom objects as keys for
collectionsand would like to do lookup using object, then you should properly overrideequals()andhashcode()methods.Also read:
Overriding equals and hashCode in Java