I need a Map
sized 1 and began to wonder what would be best, a TreeMap
or a HashMap
?
My thought is that TreeMap
would be better, as initialising and adding a value to a HashMap
will cause it to create a table of 15 entries, whereas I believe TreeMap
is a red-black tree implementation, which at size one will simply have a root node.
With that said, I suppose it depends on the hashCode
/ compareTo
for the key of the HashMap
/ TreeMap
respectively.
Ultimately, I suppose it really doesn't matter in terms of performance, I'm thinking in terms of best practice. I guess the best performance would come from a custom one entry Map
implementation but that is just a bit ridiculous.
The canonical way of doing this is to use
Collections.singletonMap()
Nice and simple, provided that you also require (or at least, don't mind) immutability.
And yes, internally it is implemented as a custom single-node
Map
.As a complete aside, you can create a
HashMap
with a single bucket if in the constructor you specify acapacity
of 1 and aloadFactor
that is greater than the number of elements you want to put in. But memory-wise that would still be a bit of a waste as you'd have the overhead of theEntry
array, theEntry
object and all the other fieldsHashMap
has (like load factor, size, resize treshold).