Java: map with any enumeration as key

How can I declare a card whose key can have any enumeration?

For example, I have two listings Fruit and Vegetable.

How can I declare a map where the key can be both fruits and vegetables, but only listings, not objects?

I mean, something like

Map<???, String> myMap... 
+7
java collections generics enums
source share
2 answers
  • You can use java.lang.Enum as a key.

     enum Fruit { Apple } Map<java.lang.Enum<?>, String> mp = new HashMap<>(); mp.put(Fruit.Apple, "myapple"); 
  • Create an interface that will be implemented in your listings. This method gives you more control.

     interface MyEnum{} enum Fruit implements MyEnum { Apple } Map<MyEnum, String> mp = new HashMap<>(); mp.put(Fruit.Apple, "myapple"); 
+18
source share

You must have a common supertype for your two enumerations if you want to declare a map where the key can be an instance of two types. A card can have only one type of key, but if you have one type with two subtypes, then this is normal.

You cannot change the superclass for enums (it is always java.lang.Enum ), but you can force them to implement interfaces. So what you can do is the following:

  interface FruitOrVegetable { } enum Fruit implements FruitOrVegetable { } enum Vegetable implements FruitOrVegetable { } class MyClass { Map<FruitOrVegetable, String> myMap; } 

Question: What is the general behavior of Fruit and Vegetable enumerations that you can include in the interface. An interface without behavior is pretty pointless. You always need to do instanceof checks and castings to treat something like Fruit or Vegetable .

Perhaps in your case you really need a single enumeration of FruitOrVegetable - if you want to be able to handle them interchangeably.

+8
source share

All Articles