0

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 .

manu endla
  • 301
  • 4
  • 19
  • 7
    It's not 16 *bits* - it's 16 *entries*. – Jon Skeet Sep 05 '14 at 10:50
  • 3
    Why would someone use a `Hashmap` only for one key/value pair? – mostruash Sep 05 '14 at 10:53
  • This is a prime example of a problem not being a problem unless you make it a problem. If you don't apply the word "waste", there is no problem here. More space is reserved than you use. So what? That happens under the hood whether you like it or not; research "memory alignment". Even if you use only 1 byte of memory, likely 8 bytes are actually used up in the process depending on the CPU architecture. http://stackoverflow.com/questions/381244/purpose-of-memory-alignment – Gimby Sep 05 '14 at 12:05
  • Now that you've accepted a different answer, it sounds like you didn't need a map to start with. In future, please be clearer about what you *actually* need - I answered the question you asked, but it appears that's not what you actually needed. – Jon Skeet Nov 28 '14 at 09:21

2 Answers2

11

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Does this add a little boost to performance in term of memory? – shareef Nov 12 '20 at 03:53
  • 1
    @shareef: Well it reduces how much memory is required, which potentially the frequency of garbage collection, but I'd be surprised to see it be measurable. – Jon Skeet Nov 12 '20 at 06:55
2

If you only need a pair of immutable values, you can use Pair class.

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.