HashMap实现原理:容量、负载因子、hash与定位都搞定了吗?( 八 )

针对HashMap的使用 , 此处要注意覆写hashCode和equals方法时的两个重点:

  • 覆写后 , 一定要保证equals判断相等的时候 , hashCode的返回值也相等 。

  • 对于选作key的类 , 要保证调用put与get时hashCode的返回值相等 , equals的性质相同 。

resize

resize是HashMap中最难理解的部分 。

调用put方法时 , 如果发现目前的bucket占用程度已经超过了loadFactor , 就会发生resize 。 简单的说就是把bucket扩充为2倍 , 之后重新计算index , 把节点再放到新的bucket中 。

javadoc中这样说:

Initializes or doubles table size. If null allocates in accord with initial capacity target held in field threshold. Otherwise because we are using power-of-two expansion the elements from each bin must either stay at same index or move with a power of two offset in the new table.

推荐阅读