I habitually use HashMap
in my programs, since I know it is usually the most efficient (if properly used) and can cope with large maps easily. I know about EnumMap
which is very useful for enumeration keys, but often I am generating a small map which will never get very big, is likely to be discarded pretty soon, and has no concurrency issues.
Is HashMap<K,V>
too complicated for these small, local and temporary uses? Is there another, simple, implementation which I can use in these cases?
I think I'm looking for a Map
implementation which is analogous to ArrayList
for List
. Does it exist?
Added later after responses:
Here is a scenario where a slow but very simple implementation might be better -- when I have many, many of these Map
s. Suppose, for example, I have a million or so of these tiny little maps, each with a handful (often less than three) of entries. I have a low reference rate -- perhaps I don't actually reference them before they are discarded most of the time. Is it still the case that HashMap
is the best choice for them?
Resource utilisation is more than just speed -- I would like something that doesn't fragment the heap a lot and make GCs take a long time, for example.
It may be that HashMap
is the right answer, but this is not a case of premature optimisation (or at least it may not be).
Added much later after some thought:
I decided to hand-code my own SmallMap
. It is easy to make one with AbstractMap
. I have also added a couple of constructors so that a SmallMap
can be constructed from an existing Map
.
Along the way I had to decide how to represent Entry
s and to implement SmallSet
for the entrySet
method.
I learned a lot by coding (and unit-testing this) and want to share this, in case anyone else wants one. It is on github here.