Ask Your Question
1

What is the internal process of HashMap functioning?

asked 2023-03-10 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-04-15 00:00:00 +0000

ladyg gravatar image

When a new element is added to a HashMap, it goes through the following internal process:

  1. The hashcode for the key is computed using the key's own hashcode() method or a null check if the key is null.

  2. The hash code is then converted to an index within the hash table using the modulo operator (%).

  3. If there is no element present in that index, a new entry is created at that position, and the key-value pair is added.

  4. If there is already an element present, then a collision has occurred, and a linked list is formed starting from that index. The new key-value pair is added to the end of this linked list.

  5. If the number of elements in a linked list at any index exceeds a certain threshold, the linked list is converted into a tree to improve performance.

  6. If the number of elements in the HashMap exceeds a certain capacity, the HashMap is resized, and all elements are rehashed to fit into the new table.

  7. When looking up an element by key, the same hashcode and conversion to index operation are done, and the linked list or tree at that index is searched for the key.

Overall, the HashMap provides a fast way to store and retrieve key-value pairs by using an efficient hashing function and handling collisions well.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-10 11:00:00 +0000

Seen: 15 times

Last updated: Apr 15 '22