Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement equals and hashcode for enum classes

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?

like image 741
Vineet Singla Avatar asked Mar 20 '23 19:03

Vineet Singla


1 Answers

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,

like image 172
Anders R. Bystrup Avatar answered Mar 31 '23 21:03

Anders R. Bystrup