Hi I have a situation where I have to store a single key value pair to my Hashmap . The map size is always constant. i.e., 1 . But default size of hash map is 16 bits . Here am almost wasting nearly 15 bits. Is there any way to limit the size of the hashmap.
Thanks in Advance for your valuable suggestions .
You can provide an initial capacity in the HashMap
constructor:
Map<String> map = new HashMap<>(1);
It looks like that is genuinely obeyed in the implementation I'm looking at, but I can easily imagine some implementations having a "minimum viable capacity" such as 16. You'd have to be creating a large number of maps for this to really be an issue.
On the other hand, if you really only need a single-entry map and you're in a performance-sensitive situation, I would suggest you might not want to use HashMap
at all. It wouldn't be hard to write a Map
implementation which knew that it always had exactly one entry (which would presumably be provided on construction). If your code depends on having a HashMap
rather than a Map
, you should check whether you really want that top be the case.
See more on this question at Stackoverflow