Reputation: 301
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 .
Upvotes: 0
Views: 9626
Reputation: 46
If you only need a pair of immutable values, you can use Pair
class.
You always can keep the structure with this class, just use getLeft() for getting the key, and getRight() to return the value of your object.
Upvotes: 2
Reputation: 1500665
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.
Upvotes: 11