8

How can I declare Map whose key can have any enum?

For example, I have two enum Fruit and Vegetable.

How can I declare map where key can be both Fruit and Vegetable, but only enumerations, not Object?

I mean, something like

Map<???, String> myMap...
0

2 Answers 2

17
  1. You can use java.lang.Enum as key.

    enum Fruit {
        Apple
    }
    
    Map<java.lang.Enum<?>, String> mp = new HashMap<>();
    mp.put(Fruit.Apple, "myapple");
    
  2. Create interface to be implemented in your enums. This method give you more control.

    interface MyEnum{}
    
    enum Fruit implements MyEnum {
        Apple
    }
    
    Map<MyEnum, String> mp = new HashMap<>();
    mp.put(Fruit.Apple, "myapple");
    
Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest to use an EnumMap instead of a HashMap, as it is optimized for maps with enum as keys.
7

You need to have a common supertype for your two enums if you want to declare a map where instance of two types can be the key. A map can only have one key type, but if you have one type with two subtypes, then that is ok.

You cannot change the superclass for enums (it's always java.lang.Enum), but you can make them implement interfaces. So what you can do is this:

 interface FruitOrVegetable {
 }

 enum Fruit implements FruitOrVegetable {
 }

 enum Vegetable implements FruitOrVegetable {
 }

 class MyClass {
     Map<FruitOrVegetable, String> myMap;
 }

The question is: what is the shared behaviour of the enums Fruit and Vegetable that you can include in the interface. An interface without behaviour is pretty pointless. You'd constantly need to do instanceof checks and casts to treat something as a Fruit or Vegetable.

Maybe in your case, you actually need a single enum FruitOrVegetable - if you want to be able to treat them interchangeably.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.