3

Is there a more efficient and specialized implementation of a Map collection where Enum objects can serve as keys?

Andrey
  • 8,882
  • 10
  • 58
  • 82

3 Answers3

17

Yes. EnumMap is precisely that; an efficient implementation of the Map interface, in which the key type must be an enum:

From the API documentation:

Class EnumMap<K extends Enum<K>,V>

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Example usage:

Map<MyEnum, String> map = new EnumMap<MyEnum, String>(MyEnum.class);
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Yes... please check existing answers before replying. This was a self-answer post. – Andrey Jun 13 '10 at 00:43
  • 2
    So you, 1. post an easy question of which you know the answer. 2. Write up a half-baked answer yourself immediately. 3. Down-vote other answers because you feel that it was somehow "your question to answer"? I don't get it.. why?? for reputation? – aioobe Jun 13 '10 at 07:37
  • 1
    while I support your confusion, and certainly oppose the OP's downvote, I don't think there was a need for another answer about `EnumMap`. (That's why I deleted mine :) ) – Bozho Jun 13 '10 at 08:56
  • 3
    I wrote my answer because I didn't get why the previous answer included the LibraryItem interface and a NavigableSet of LibraryItems to illustrate the use of an EnumMap. If I knew the OP wasn't interested in an answer to the question I obviously wouldn't have bothered. :) – aioobe Jun 13 '10 at 09:21
  • 1) There's nothing wrong with self-answer posts, read the FAQ. I made this post because I knew EnumMap is not widely known and thought it would be beneficial to a lot of devs if they were aware of its existence. 2) My answer was not "half-baked" since it included an example as well as a link to the API. The only mistake I had was to use LibraryItem instead of LibraryItemType in one place which was in fact fixed by Donal, thank you Donal for catching that. So as far as I can see your answer was redundant... but that's why the community exists to settle disputes like these for us. – Andrey Jun 13 '10 at 15:46
2

BTW, it's simpler to write:

Map<MyEnum, String> map = new EnumMap<>(MyEnum.class);

There's no need to repeat the types. This can make the code a lot easier to read.

Bruce
  • 23
  • 3
-1

I learned this recently after I accidentally stumbled upon the answer in the Java API. If you ever have a map that uses enums as keys make sure you use EnumMap. It's very simple and much more efficient:

public interface LibraryItem{ ... }

public enum LibraryItemType{ BOOK, CD, VHS, AUDIO; ... }

Map<LibraryItemType, NavigableSet<LibraryItem>> itemsByType =
    new EnumMap<>(LibraryItemType.class);
Bruce
  • 23
  • 3
Andrey
  • 8,882
  • 10
  • 58
  • 82