Call contains key on a hash map with a custom class

I have a Color class that I put in a hashmap. I would like to call containsKey in hashmap to make sure the object is already present in 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 would like System.out return true, because the key already on the map, c , has name red

How can this be achieved?

+8
java hashmap
source share
1 answer

The custom Color class must override the equals() and hashcode() methods to achieve the desired result.

When you use custom objects as keys for collections and want to search using the object , you must correctly override the equals() and hashcode() methods.

Also read:

Overriding peers and hashCode in Java

+14
source share

All Articles