JimJim2000 JimJim2000 - 3 months ago 17
Java Question

Java: Map with any enum as key

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...

Answer
  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");
    
Comments