top of page

How HashMap works Internally

If you're a Java developer then, it's not possible that you haven't used hashmap in your recent past (not talking about people like Jignesh).


As the name suggests, yes hashmap internally uses hashing but the question arises what exactly hashing is?

Hashing is a technique that takes input and returns one value and the value that you got in return is processed by some algorithm and algorithms can vary according to their use.


Now, back to our main question how does HashMap work?


First, when you declare one empty hashmap in your code same moment java internally creates one array yes array! of size 16. No, I am joking that's completely true. The size of that array grows in the power of 2.


Now what exactly we are storing there you might think hashcode! No, not hashcode every index of that array gets initialized by a linked list yeah! you read it correctly so let's learn the whole algorithm in simple steps.





After checking the above picture you might get one question "ye sala node ko kon bataya ki Kha chipkana hai, ki sala fevicol hai kahi bhi chipak gaya" So my friends here our hashing technique comes into the picture. For every creation, we will have one unique value known as hashcode but the hashcode value can be of size 10,11 or even can be bigger so, here basically in hashmap n&n-1 is using this will provide a value which you can fit in an array of size 16 i.e.(0-15) now again you can brainstorm yourself that what if we get same value again so, here is the answer that, first it will check with equals method that provided node is different or not if not then the value will be overridden by new one else will be appended in the list.


So, that's how hashmap works.


Now, if somebody asks you why hashmap doesn't keep its insertion order then you can tell "sab hashing ka khela hai" whatever index hashing will provide that will become index if an index is same then got appended in the list.





Kommentare


bottom of page