Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 353
Pavel_K Avatar asked Aug 05 '16 05:08

Pavel_K


2 Answers

  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");
    
like image 109
afzalex Avatar answered Oct 21 '22 16:10

afzalex


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.

like image 45
Erwin Bolwidt Avatar answered Oct 21 '22 18:10

Erwin Bolwidt