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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With