1

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.

4

3 回答 3

7

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.

于 2013-09-01T20:59:05.693 回答
2

hashmap 的查找复杂度为 O(1),而迭代自然有 O( n )。也就是说,对于只有 5 个枚举值,平均而言迭代可能会更快,并且当你只是迭代时它不需要额外的数据结构.values()

于 2013-09-01T21:07:06.223 回答
1

如果你有一个 Enum 作为键,你应该使用一个 EnumMap。这基本上包装了一个值数组,并且比使用 HashMap 更快。

于 2013-09-01T21:24:11.533 回答