Why does EnumMap<T>.keySet() return a Set<T>() and not an EnumSet<T>()?
java
Solution
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.
Problem
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.