0

I was going through Rehashing process in hashmap or hashtable which explains the beautiful concept of HashMap rehashing. I have a question about it.

Consider a case where initial capacity of HashMap is 16 and load factor is 0.75. Now, 12 elements are added to the HashMap, but they all end up in the same bucket due to a poor hashCode implementation. The other 15 buckets do not contain any elements. Will the HashMap rehash?

Community
  • 1
  • 1
Gaurav Seth
  • 186
  • 3
  • 11

1 Answers1

1

Actually, at least with the current implementation of HashMap, collisions don't affect rehashing. See, for example, lines 661-662 at the end of HashMap.putVal, which simply check

if (++size > threshold)
    resize();

where threshold is (capacity * load factor), cached in a field for speed (avoiding a floating-point operation).

HashMap deals with overfull buckets by converting the buckets from linked lists to balanced trees.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
  • So, when will rehashing happen in this case? Total capacity is 16 and 12 elements are already added into one bucket (due to poor hash code implementation). – Gaurav Seth Dec 13 '15 at 17:45
  • Rehashing will happen at 13 elements, because the threshold is 16 * .75 == 12. But that has _nothing to do with buckets_! – Jeffrey Bosboom Dec 13 '15 at 20:41