How does a HashMap consume memory?

I am afraid of downvotes. In any case, just as ArrayList will have contiguous memory allocation, LinkedList will have random memory allocation, how does a HashMap take memory? Does it also take random chunks in memory? Can I be instructed with a memory diagram about how maps and local links are inside memory?

Hope this is not a bs question. I did not find much information about the memory card allocation diagram.

EDIT . The question I ask has nothing to do with debugging / profiling. This is exactly how the HashMap fits into memory. I did not know about him.

+6
source share
2 answers

This is a combination of both.

There is a basic, contiguous array that supports HashMap . Elements of this array are actually linked lists. Each time you add a key-value pair to a card, the key is hashed, and a linked list entry is added to the corresponding slot in the support array (i.e., the slot corresponding to the value of the hash key).

For example, a map that maps k to v might look like this:

  0 1 2 3 4 5 6 7
 + --- + --- + --- + --- + --- + --- + --- + --- +
 |  |  |  |  |  |  |  |  |
 + -X - + - X - + - ↓ - + - X - + - X - + - X - + - X - + - X- +
           ↓
           ↓
         + --- +
         |  k |
         |  - |
         |  v |
         + --- +

There is a long β€œtable” that supports the map, and a record that supports the specific k -to- v pairing.

You are probably best off looking at the HashMap source for yourself.

+6
source

A hashmap is always an array, where a hash code can be defined to get the index of an array element (In jdk is a record). Therefore, it must also have an adjacent memory.

0
source

All Articles