HashMap or TreeMap for map size 1

I need a size of Mapsize 1 and started to wonder what would be better, TreeMapor HashMap?

I thought it TreeMapwould be better, since initializing and adding a value to it HashMapwill make it create a table of 15 records, whereas I believe that it TreeMapis an implementation of a red-black tree, which in size one will simply have the root root.

With that said, I believe that it depends on hashCode/ compareTofor the key HashMap/, TreeMaprespectively.

Ultimately, I suppose it really doesn't matter in terms of performance, I think in terms of best practice. I guess the best performance will come from a custom implementation Map, but this is a little ridiculous.

+4
source share
2 answers

The canonical way to do this is to use Collections.singletonMap()

Pleasant and simple if you also demand (or at least do not mind) immutability.

And yes, internally it is implemented as a custom single node Map.


HashMap , capacity 1 loadFactor, , , . , - , Entry, Entry HashMap (, , , ).

+7

key to value structure, SimpleEntry<K,V>, Map.Entry<K,V>

+1

All Articles