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.
Erwin bolwidt
source share