Tuesday 20 February 2018

Internal Collection working

HashMap Internal Working

HashMap always works based on Hashing. Because which helps to faster search.
HashMap having put(Object k, Value v) and get(Object k) methods.
Will see How HashMap works Internally by using these 2 methods.

Bucket : Bucket is one element in HashMap Array. Nodes can store into the bucket. 2 or more nodes are same in each bucket then it will store by using linked list as like below.

Key k = "king"
Value v = "100"
put(Key k, Value v) 
{
       hash(k) ->1021467
       index = hash & (n-1) -> 3
}

Based on key will find the HashValue
Based on HashValue will find the IndexValue.
HashValue & key & value will sit. @ indexValue,
If it same Index it will store in next node of Linked List.(Because in linked list always last node is null).


get(Object key)
{
hash(key) -> 1021467
index = hash & (n - 1) ->3
}

Based on Key value it will find the HashValue.
Based on Hashvalue it will find the Index.
Based on Index value it will return the value of that key.

If Index  value is same for different key then it will take the Hash Code and compares and return the value.

Ex : Key = "King" then Hashvalue = 1021467 so it return index = 3. Based on index and hashvalue it return the value = 100.
If Key = "Queen" then HashValue = 1024241 so it return index = 3. Both index are same so now it take the Hash value and compare in another node of the linked list. If both Hash values are same then it will return the value= 90.

ArrayList Internal Working



LinkedList Internal Working


No comments:

Post a Comment

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...