Java集合之HashMap源码解析

Java集合系列的源码解析,分析代码的版本均为:Sun JDK1.7

这篇文章fuck的是HashMap,为什么先选择它呢,因为Android开发中最常用的数据集合就是HashMap和ArrayList,这里先Fuck HashMap。

通过本篇文章你可以知道下面几点:
1.HashMap内部采用的数据结构——>HashMap内部采用的是数组加单链表来实现的,单链表的插入为头插法。(如果对链表的理论不熟悉可以参考:线性表

2.HashMap的扩容机制——>大于阀值,且当前索引处的值非null,则直接扩容1倍。

3.HashMap是如何解决碰撞问题的——>拉链法,即采用链表的形式,关于散列表


创建HashMap的对象有4种姿势,比如像下面这样:

代码清单1:

/**HashMap源码解析使用**/
public class HashMapTest {
public static void main(String[] args) {
	HashMap<String, String> hashMap=new HashMap<>(4,0.25f);
	HashMap<String, String> hashMap2=new HashMap<>(3);
	HashMap<String, String> hashMap3=new HashMap<>(3, 1);
	HashMap<String , String> tmp=new HashMap<>();
	HashMap<String, String> hashMap4=new HashMap<>(tmp);
	hashMap.put(null, null);
	System.out.println(hashMap.get(null));
	int a=(11 > 1) ? Integer.highestOneBit((11- 1) << 1) : 1;//
	System.out.println(a);
	hashMap.put("G1", "1");
	hashMap.put("G2", "2");
	hashMap.put("G3", "3");
	hashMap.put("G4", "4");
	hashMap.put("G5", "5");
	hashMap.put("G6", "6");
	hashMap.put("G7", "7");
	hashMap.put("G8", "8");
	hashMap.put("G9", "9");
	hashMap.put("G10", "10");
	hashMap.put("G11", "11");
	hashMap.put("G12", "12");
	System.out.println(hashMap.keySet().toString());//
	System.out.println(hashMap.values().toString());
	System.out.println(hashMap.entrySet().toString());
	

}
}


看下HashMap的构造函数:

代码清单2:

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认容量16
    static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认装载因子 0.75
    static final Entry<?,?>[] EMPTY_TABLE = {};
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;//这里注意一下,transient修饰的变量不能序列化,而且table的长度是2的幂,存数据的载体,这是一个对象数组
    transient int size;//
    int threshold;//阀值,用于判断是否需要调整HashMap的容量(threshold=loadFactor*capacity)
    final float loadFactor;//装载因子,一旦指定不可改变
    transient int modCount;//该hashMap总共被修改了多少次
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)//如果大于最大值,则设为最大值
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        threshold = initialCapacity;//初始阀值为初始容量
        init();//空方法,这里不用管这个方法,没有多大的实际意义
    }
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);//这句话等价于:this(16,0.75);
    }
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);
        putAllForCreate(m);
    }


在上面的代码中,我们发现构造函数中没有对table进行初始化,那么数据存储在哪呢?一般new HashMap之后我们都要使用put(object object)或putAll(Map<object,object>)来进行存数据,其实putAll内部是经过循环遍历其参数来调用put来完成功能的。

下面我们先着重看一下put方法:

代码清单3:

 public V put(K key, V value) {
        if (table == EMPTY_TABLE) {//如果为空则进行初始化,这里就解决了构造函数中没有初始化table的问题
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);//从这里可以看到hashmap是可以接收key为null的键值对,这个方法没有什么好讲的,就不展开了。
        int hash = hash(key);//计算哈希值
        int i = indexFor(hash, table.length);//通过哈希值来获取数组下标
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {//这里e=e.next是当发生碰撞时解决冲突的产物
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//如果已有相应的键值对,则更新其值。
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(hash, key, value, i);//加入新的键值对
        return null;
    }


关于put方法,我们根据上面的注释就可以明白大致的意思,这里先展开看一下inflateTable(threshold)这个函数,代码如下:

代码清单4:

  /**
     * Inflates the table,在这个函数的方法体中,我们可以看到table数组的实际大小要比我们调用构造函数传入的值大,原因再于减一左移调整2幂
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);//比如tosize=11则capacity=16。
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);//重新设置阀值,
        table = new Entry[capacity];//初始化table,
        initHashSeedAsNeeded(capacity);//初始化哈希种子
    }
private static int roundUpToPowerOf2(int number) {//调整大小,返回一个2幂的值
        // assert number >= 0 : "number must be non-negative";
        return number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;//highestOneBit的作用是:如果一个数是0, 则返回0;如果是负数, 则返回 -2147483648:【1000,0000,0000,0000,0000,0000,0000,0000】(二进制表示的数);如果是正数, 返回的则是跟它最靠近的比它小的2的N次方
    }
 /**
     * Initialize the hashing mask value. We defer initialization until we
     * really need it.
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

代码清单4的最主要任务就是new Entry[ capacity ],我们继续put方法,将addEntry展开,如代码清单5:

代码清单5:

//该函数的主要职责是根据需要调整table的大小   
 void addEntry(int hash, K key, V value, int bucketIndex) {
//如果当前键值对的数量已经大于阀值并且buckeIndex位置上有值(说明发生了碰撞),进行扩容处理。
        if ((size >= threshold) && (null != table[bucketIndex])) {从这里我们可以看到,并不是键值对的值到达表长才开始扩容,而是达到阀值就开始扩容。
//扩容扩容,直接两倍,这里扩容扩的是数组的容量,这里直接乘以2是因为table.length的值本身就已经调整成2的幂
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;//重新计算hash值
            bucketIndex = indexFor(hash, table.length);
        }
        createEntry(hash, key, value, bucketIndex);
    }
 void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);//从这两句代码可以看出,这里的单向链表采用的是头插法。
        size++;//size的值只在这里更新,即只有在创建具体的键值对时才会更新值
    }
 void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {//如果当前容量是最大值,则阀值为最大值,并返回
            threshold = Integer.MAX_VALUE;
            return;
        }
        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable, initHashSeedAsNeeded(newCapacity));//迁移键值对
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);//更新阀值
    }
 /**
     * 这个迁移代码的核心,迁移元素的函数并不会对size的进行改变,因为迁移并没有增加元素。
     */
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);//这个迁移逻辑其实是把单链表反序的操作,不影响,因为HashMap本身并不对键值对有顺序要求。
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }


通过代码清单3至5的代码注释,我们已经清楚地了解了put操作的全过程。存的过程通晓了,存数据就是为了取,我们下面来一起看一下如何取数据,请看代码清单6:

代码清单6:

 public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);
        return null == entry ? null : entry.getValue();
    }
    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {//从这里可以看出key为null其哈希值为0
            if (e.key == null)
                return e.value;
        }
        return null;
    }
 final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }


代码清单6整个逻辑比较简单,其实就是两步走,定位数组元素的索引,然后遍历单链表,若找到相应的键值对则返回value,没有直接返回null。

我觉得我们有必要看一下hash相关的函数以及数组元素的索引定位,如代码清单7:

代码清单7:

        
        transient int hashSeed = 0;

        final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }
//这个hash函数的作用是计算哈希值,
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        h ^= k.hashCode();

        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);//做了4次扰动处理,其实就是为了减少碰撞,jdk1.8中对于该函数进行了优化,只做了一次扰动处理。
    }
//根据哈希值来获取table数组的索引
   
    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);//当length为2^n时,这句代码等价于h%length,其实在hashmap的初始容量或者以及动态扩容的容量都是2^n,所以这里其实可以理解为求模的运算
    }


开篇的3个问题已经解释清楚了,到这里又引出新的问题:

为什么容量一定要是2的幂(即2^n)呢?

要解释为什么HashMap的长度是2的整次幂,就必须indexFor和hash函数一起来分析。

h&(length-1)中的length-1正好相当于一个"地位掩码",“与”操作的结果就是散列值的高位全部归零,只保留低位值,用来做数组下标访问,这样保证了求得的索引indx即indexFor函数的返回值不会发生越界情况。这里我们看两组数据:

16:0000 0000 0000 0000 0000 0000 0001 0000 减去1=15:0000 0000 0000 0000 0000 0000 0000 1111

32:0000 0000 0000 0000 0000 0000 0010 0000 减去1=31:0000 0000 0000 0000 0000 0000 0001 1111

第一组数据:

---------h=8,length=16,indexFor返回值:8------------------------

0000 0000 0000 0000 0000 0000 0000 0000 1000(h)

0000 0000 0000 0000 0000 0000 0000 0000 1111 (length-1)

0000 0000 0000 0000 0000 0000 0000 0000 1000 (index)

---------h=24,length=16,indexFor返回值:8------------------------

0000 0000 0000 0000 0000 0000 0000 0001 1000

0000 0000 0000 0000 0000 0000 0000 0000 1111

0000 0000 0000 0000 0000 0000 0000 0000 1000

---------h=56,length=16,indexFor返回值:8------------------------

0000 0000 0000 0000 0000 0000 0000 0011 1000

0000 0000 0000 0000 0000 0000 0000 0000 1111

0000 0000 0000 0000 0000 0000 0000 0000 1000


第二组数据:

---------h=8,length=32,indexFor返回值:8------------------------

0000 0000 0000 0000 0000 0000 0000 0000 1000

0000 0000 0000 0000 0000 0000 0000 0001 1111

0000 0000 0000 0000 0000 0000 0000 0000 1000

---------h=24,length=32,indexFor返回值:24------------------------

0000 0000 0000 0000 0000 0000 0000 0001 1000

0000 0000 0000 0000 0000 0000 0000 0001 1111

0000 0000 0000 0000 0000 0000 0000 0001 1000

---------h=56,length=32,indexFor返回值:24------------------------

0000 0000 0000 0000 0000 0000 0000 0011 1000

0000 0000 0000 0000 0000 0000 0000 0001 1111

0000 0000 0000 0000 0000 0000 0000 0001 1000

看到没有如果我们不对hash进行扰动处理,直接进行求模运算,则发生了碰撞。来我们对上面的数据进行骚动,额,不对,进行扰动。

---------h=8,r_h=8,length=16,indexFor返回值:8------------------------

0000 0000 0000 0000 0000 0000 0000 0000 1000 (h)

0000 0000 0000 0000 0000 0000 0000 0000 1000 (r_h)

0000 0000 0000 0000 0000 0000 0000 0000 1111 (length-1)

0000 0000 0000 0000 0000 0000 0000 0000 1000 (index)

---------h=24,r_h=25,length=16,indexFor返回值:9------------------------

0000 0000 0000 0000 0000 0000 0000 0001 1000 (h)

0000 0000 0000 0000 0000 0000 0000 0001 1001 (r_h)

0000 0000 0000 0000 0000 0000 0000 0000 1111 (length-1)

0000 0000 0000 0000 0000 0000 0000 0000 1001 (index)

---------h=56,r_h=59,length=16,indexFor返回值:11------------------------

0000 0000 0000 0000 0000 0000 0000 0011 1000 (h)

0000 0000 0000 0000 0000 0000 0000 0011 1011 (r_h)

0000 0000 0000 0000 0000 0000 0000 0000 1111 (length-1)

0000 0000 0000 0000 0000 0000 0000 0000 1011 (index)


看到没,就因为对hash进行了扰动处理,所以第一组数据样本发生的碰撞消除了。r_h的求值是根据:h ^= (h >>> 20) ^ (h >>> 12);h ^ (h >>> 7) ^ (h >>> 4);通过上面的数据,我相信大家已经明白了hash以及indexFor两个函数了。HashMap的源码分析到此结束,其余部分的代码自行了解,此篇文章是基于jdk1.7的代码来分析的,至于1.8的改动,有时间会再出一篇文章。


转载请注明出处:http://blog.csdn.net/android_jiangjun/article/details/78436388

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值