Pergunta

I fear downvotes. Anyways, just like an ArrayList would have a contiguous memory allocation, a LinkedList would have a random memory allocation, how does HashMap occupy memory? Does it also take random chunks in the memory? Can I be briefed with a memory diagram of how map's buckets and the LinkedLists inside are located in the memory?

I hope this is not a bs question. Did not find much of information regarding Map's memory allocation diagram.

EDIT: The question I put has nothing to do with debugging/profiling. It's just about how a HashMap fits into the memory. I was unclear about it.

Foi útil?

Solução

It's a combination of both.

There is an underlying, contiguous array that backs HashMap. The elements of this array are actually singly linked lists. Each time you add a key-value pair to the map, the key is hashed and a linked list entry is added to the corresponding slot of the backing array (i.e. the slot corresponding to the key's hash value).

For instance, 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 backs the map, and an entry that supports the specific k-to-v pairing.

It would probably be best for you to take a look at the HashMap source for yourself.

Outras dicas

A hashmap is always an array where the hashcode can be determined to get the index of the array element(In jdk this is the entry) . Therefore, it should take a contiguous memory as well.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top