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...
You can use java.lang.Enum
as key.
enum Fruit {
Apple
}
Map<java.lang.Enum<?>, String> mp = new HashMap<>();
mp.put(Fruit.Apple, "myapple");
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With