I'm writing a program with a lot of enumerations, and I'm having to return the keyset of an EnumMap a lot. But EnumMap.keySet()
returns a Set()
, so in order to get the EnumSet
I want, I have to use a cast:
EnumMap<SomeEnum, Object> myMap = getMap();
EnumSet<SomeEnum> myEnum = (EnumSet<SomeEnum>) myMap.keySet();
If I don't cast, the compiler will complain of a type mismatch; it cannot convert from Set<SomeEnum>
to EnumSet<SomeEnum>
. It seems unnecessary to have to cast this, as the keys of an EnumMap will always be an enumeration. Does anyone know why the keySet()
method was constructed this way? I've thought at times it might have something to do with EnumSet being an abstract class, but surely EnumMap
could just return whatever the factory method of EnumSet
provides.
Cheers, all!
EDIT: I'm very sorry, the above code throws a CastClassException
. You could get the EnumSet by using
EnumSet<SomeEnum> myEnum = EnumSet.copyOf(myMap.keySet());
I really should have checked before posting.
I think its because the keySet
is not an EnumSet
. ;)
The reason it is not is that the keySet
is a view onto the underlying map.
myMap.keySet().removeAll(keysToRemove); // removes multiple keys.
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