How to implement equals and hashcode for enum classes
enums, hashmap, java
Solution
The class `java.lang.Enum` declare both `equals()` and `hashCode()` as `final`, thus you'll get compiler errors trying to override them.
That being said, your example above works as you desire - if you add `AlphaTypes.Common` and `BetaTypes.Common` to a `Map` you'll get a map with two elements:
public static void main( String[] args ) throws Exception
{
Map<Types,Object> map = new HashMap<Types,Object>();
map.put( AlphaTypes.Common , "b" );
map.put( BetaTypes.Common , "b" );
System.out.println( "size=" + map.size());
}
size=2
Cheers,
Problem
I have an interface name Types ``` public interface Types { public String getName(); } ``` Two enum classes are extending this interface like ``` public enum AlphaTypes implements Types { Alpha("alpha"),Common("common") private String name; private AlphaTypes(String name) { this.name = name; } @Override public String getName() { return name; } } public enum BetaTypes implements Types { Beta("beta"),Common("common") private String name; private BetaTypes(String name) { this.name = name; } @Override public String getName() { return name; } } ``` The requirement is have a map which takes Types as key like `Map<Types,Object> map;` How to implement equals and hashcode, such that the map keys are unique even for common enum values?