hashmap rehash过程

面试中被问到hashmap的rehash过程,有点搞晕了,rehash时get操作是怎么进行的? rehash过程中又有put操作 发生了什么? 可以帮忙解释一下吗?

阅读 6.5k
1 个回答

HashMap (Java Platform SE 8) 文档中有提到

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

简单说 rehash 就是因为 HashMap 的空间不够用了,所以需要分配一个大一点的空间,然后保存在里面的内容需要重新计算 hash。

HashMap 不是线程安全的,所以在 rehash 的过程中又有 put 操作……完全不可预料会发生什么,有可能是很坏的事情,线程安全是个大问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题