Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap or TreeMap for Map specifically sized 1

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 TreeMapis 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.

like image 700
Robert Bain Avatar asked Feb 10 '23 20:02

Robert Bain


1 Answers

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).

like image 118
biziclop Avatar answered Feb 12 '23 09:02

biziclop