---
title: "hashmap源码阅读"
author: "youngphy"
date: "2013-10-22T11:20:38Z"
tags: []
categories: ["编程语言"]
slug: "hashmap"
draft: false
lastmod: "2013-10-22T11:20:38Z"
id: 1962228
url: "https://youngphy.iteye.com/blog/1962228"
---

泛泛读过几次，整体设计思路也大体了解，但长久不接触，触及一些细节代码时，还是陷入了思考泥潭，反省，应该存在细节盲点，又从整体和细节仔细品味了一番，记录。


```java
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
```

单看hash方法很难理解，需要一起看indexFor方法，也就是hashmap的定位bucket方法。

```java
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
```
为了追求快，hashmap的size为2的次方，定位因此可以简单高效地用位与运算，但些方法带来一个内部问题，对于超出length的hashcode, 高位不参与定位，所以所有高位相同的对象会被indexFor定位到一个bucket, hash方法的目的就是把高位的影响弄到低位，让高位也参与到定位，解决不至于所有低位相等的对象分到同一个bucket。

核心设计思路：hash要尽量均匀的打散数据分布。无论从应用层还是核心层。
碰撞概率大的话，hash不均，造成局部数过多，hash效率有O(n)的趋势。
虽然应用层出现低位相等，高位不同的对象的概率不大，但从架构层面上考虑，需要解决所有问题，你不能保证这种小概率事件不会出现，需要解决这种小概率事件，这就是hash方法的作用。