I want to know when resizing or rehashing is happening what will happen if we try to put an element in the map .Does it goes to new increased map or the old map.
And also what is the use of the extra free space in hashmap ,which is 25% of original map size as load factor is 75%?
Perhaps this needs a coherent answer.
This question only makes sense if you have two or more threads performing operations on the
HashMap
. If you are doing that your code is not thread-safe. Its behavior is unspecified, version specific, and you are likely to have bad things happen at unpredictable times. Things like entries being lost, inexplicable NPEs, even one of your threads going into an infinite loop.You should not write code where two or more threads operate on a
HashMap
without appropriate external synchronization to avoid simultaneous operations. If you do, I cannot tell you what will happen.If you only have one thread using the
HashMap
, then the scenario you are concerned about is impossible. The resize happens during an update operation.If you have multiple threads and synchronize to prevent any simultaneous operations, then the scenario you are concerned about is impossible. The other alternative is to use
ConcurrentHashMap
which is designed to work correctly when multiple threads can red and write simultaneously. (Naturally, the code for resizing aConcurrentHashMap
is a lot more complicated. But it ensures that entries end up in the right place.)Assuming you are talking about the multi-threaded non-synchronized case, the answer is unspecified and possibly version specific. (I haven't checked the code.) For the other cases, the scenario is impossible.
It is not used. If the load factor is 75%, at least 25% of the hash slots will be empty / never used. (Until you hit the point where the hash array cannot be expanded any further for architectural reasons. But you will rarely reach that point.)
This is a performance trade-off. The Sun engineers determined / judged that a load factor of 75% would give the best trade-off between memory used and time taken to perform operations on a
HashMap
. As you increase the load factor, the space utilization gets better but most operations on theHashMap
get slower, because the average length of a hash chain increases.You are free to use a different load factor value if you want. Just be aware of the potential consequences.