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 a capacity
of 1 and a loadFactor
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 the Entry
array, the Entry
object and all the other fields HashMap
has (like load factor, size, resize treshold).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With