Suppose I have declared an enum and corresponding emummap as:
enum MyEnum {
CONSTANT1, CONSTANT2, CONSTANT3;
}
EnumMap<MyEnum, String> MyEnumMap = new EnumMap<MyEnum, String>(MyEnum.class);
I want to iterate over MyEnumMap
, for example, just to print each Entry
one by one.
What is the best approach(fastest) to iterate over keys in the following cases:
- When it is ensured that each constant in
MyEnum
is a key inMyEnumMap
- When each constant in
MyEnum
may or may not be a key inMyEnumMap
I want to choose between foreach loop using MyEnumMap.keySet()
or MyEnum.values()
. Any other approach is most welcomed.
If you take a look at code of
EnumMap#keySet()
you will notice that it returns
keySet
used internally byEnumMap
to store keys.Now each time we call
MyEnum.values()
we are getting different array filled with all enum elements. This means that first empty array is created which later needs to be filled with all enums which requires some iteration.So in first approach you are skipping iterating over enums already stored by map, while insecond approach we simply creating some temporary array which involves additional iteration over all MyEnum elements.