JimJim2000 JimJim2000 - 1 year ago 120
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 Source
  1. You can use java.lang.Enum as key.

    enum Fruit {
    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 {
    Map<MyEnum, String> mp = new HashMap<>();
    mp.put(Fruit.Apple, "myapple");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download