HashMap
is implemented in a very simpe manner but it needs a genius to understand how it is implemented. So, I have read about HashMap
in java docs. I have some small questions regarding HashMap
:
HashMap
is 16. In java docs they have given The default initial capacity - MUST be a power of two.. Any specific reason behind this?HashMap
works on basis of HashCode, Bucket and LinkedList
if i am not wrong. Then how size of HashMap
is being increased. I mean how buckets size and LinkedList size are managed.HashMap
, on basis of HashCode it directly access that particular bucket without traveling like in LinkedList
. Am I right? And other thing is that it adds element at head not at tails. What is the reason for that. Is new element added at head of LinkedList
present inside bucket to avoid tail traversing. Is my thinking correct? In the case when all the keys which you have in your hashmap turn out to have the same hashcode, then your hashmap will no longer be hashmap. It will be turned into a linked list. The lookup time will increase for the order of one (o (1)), i.e., constant time, to order of N (O (N)) that is linear time. Q6.
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program. The class of java.util.HashMap is by far one of the most important libraries of Java. Rarely is there any project which is written in java, and it does not use the library of HashMap in their implementation.
HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String.
HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value. HashMap allows null key also but only once and multiple null values.
Using powers of two simplifies the implementation and improves its performance.
E.g. to find a bucket from a hash code it can use hash & (SIZE -1) instead of abs(hash) % SIZE
Until you know how HashMap
works exactly you won't be able to answer this question. If the size of the Map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Similar to other collection classes like ArrayList
, Java HashMap
re-size itself by creating a new bucket array of size twice of previous size of HashMap
, and then start putting every old element into that new bucket array. This process is called rehashing because it also applies hash function to find new bucket location.
We store every new element at the head of the linked list to avoid tail traversing and hence at the time of resizing the entire sequence of objects in linked list gets reversed, during which there are chances of infinite loops.
Read more here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With