HashMap or TreeMap for Map specifically sized 1

110 views Asked by At

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.

2

There are 2 answers

1
biziclop On BEST ANSWER

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

1
nafas On

If you are only looking for a key to value structure you can just use SimpleEntry<K,V> class, this is basically an implementation of Map.Entry<K,V>