2

Basically i have an enum with an id.

Would it be faster to create a hashmap that would take the id and give you the enum or iterate over all the enums testing if the id provided is equal to the id of the enum, and if so returning it.

If it matters then there are 5 enums.

1
  • 7
    Unless you're doing this millions of times per second, it won't make any difference which you do with only five items. Commented Sep 1, 2013 at 20:53

3 Answers 3

8

HashMaps are specifically designed for retrieving objects via a key, and are fast even with many entries. Usually, a sequential scan of a list or similar collection would be much slower.

But if you have only 5 items, there's no real difference.

Edit: on second thoughts, with so few objects you might be better off with a sequential scan because the extra work in calculating the hash codes might outweigh the advantage. But the difference is so small it's not worth bothering about.

Sign up to request clarification or add additional context in comments.

Comments

2

A hashmap has a lookup complexity of O(1), while iterating naturally has O(n). That said, for only 5 enum values the iteration will probably be faster on average, and it will not need an extra data structure when you just iterate over .values() anyway.

Comments

1

If you have an Enum as a key, you should use an EnumMap. This basically wraps an array of values and is faster than using a HashMap.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.