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.