5

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?

Vineet Singla
  • 1,609
  • 2
  • 20
  • 34
  • why not have Map> of some sort? – Ariel Pinchover Apr 24 '14 at 07:29
  • 2
    Have you tried just using it with the default implementations? Reference equality should be fine since these are `enum`s (so you won't have different instances with the same values), and I see no reason why the default `hashCode` wouldn't suffice. – jpmc26 Apr 24 '14 at 07:32
  • 4
    Remember enum members are singletons, so == is adequate as a test for equality . all enum classes implicitly extend java.lang.Enum which has final implementations of both. equals uses == and hashCode uses Object.hashCode. Try overriding them in any enum and you'll get a compiler error Possible duplicate : http://stackoverflow.com/questions/2964704/why-java-does-not-allow-overriding-equalsobject-in-an-enum – Asif Bhutto Apr 24 '14 at 07:33

1 Answers1

9

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,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55