JDK HashMap的实现原理分析

JDK HashMap的实现原理分析

HashMap的数据结构

先来看看数组和链表数据结构的特点:

数组:存储区间连续,寻址容易,插入和删除困难

链表:存储区间离散,寻址困难,插入和删除简单

HashMap的出现就是将数组和链表的优点相结合。

我们发现哈希表是由数组+链表组成的。

一些重要的属性
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //可以看到,是存放Entry<k,v>元素的数组,名为table。
    transient Entry<K,V>[] table;

    //当table的占用超过这个值,就要扩容。
    int threshold;

    //负载因子  threshold = capacity*loadFactory
    final float loadFactor;
数组的存储规则

那么如何确定数据存储在数组的哪个下标中呢?

一般根据 hash(key)&(len-1)来获得,如,数组长度为16,hash(key.hashCode())为2。我们做如下运算:

&:按位与操作,若对应的二进制位都为1,结果为1.

2 & (16-12的二进制为: 0000 0010
15的二进制:   0000 1111
结果:        0000 0010 (转换成int值为2)

最后,该元素就存放在table[2]位置上。

HashMap的基础存储结构

HashMap中有个静态内部类Entry,其属性有key,value,next,hash。key是键,value是值,next是指向下一个Entry元素的引用,hash是key.hashCode()的hash值。如下:

    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
    }
HashMap的存取实现
table初始大小

table的初始大小需要根据HashMap的构造函数来决定。

空参数构造函数
    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        //负载因子
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //阈值 当table的占用超过此值时就会扩容
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        //给table的默认长度
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

英文注释已经说明了一切,table的默认长度为16,负载因子的默认值为0.75

当然也可以看看这些常亮的值,如下:

    static final float DEFAULT_LOAD_FACTOR = 0.75f;
     static final int DEFAULT_INITIAL_CAPACITY = 16;
指定容量的构造函数

当然可以直接指定初始容量,其负载因子为默认的0.75

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
指定容量和负载因子的构造函数

创建HashMap的时候可以指定容量和负载因子,但是HashMap真正的容量并不等于你指定的值。

看下面这段代码,设置capacity的值为1,当其

  public HashMap(int initialCapacity, float loadFactor) {
        // Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;
        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }
确定数组Index

数组下标 = hash(key.hashCode())&(数组长度-1)

所以,数组下标相同,hashcode不一定相同。

   /**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
存取示例代码
简单实现
// 存储时:
int hash = key.hashCode(); // 计算key的hashcode的hash值
//将计算出来的hash与数组长度取余
int index = hash & (Entry[].length-1);
//将值赋予数组下表
Entry[index] = value;

// 取值时:
int hash = key.hashCode();
int index = hash &( Entry[].length - 1 );
return Entry[index];
put的具体实现

put往HashMap中存值

 public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value); //null总是放在table下标为0的链表中

        //计算key的hashCode的hash值
        int hash = hash(key.hashCode());

        //计算要存放的数组下标
        int i = indexFor(hash, table.length);

        //遍历链表
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //如果key在链表中已存在,则替换为新value
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                //返回旧值
                return oldValue;
            }
        }

        //遍历链表完毕没有相同的key,则添加值到链表中
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

我们知道,如果在HashMap中,如果当前key已经存在,再put进去相同key的值,就会替换掉旧值。那么这个是如何实现的呢?
主要是下面这段代码:

 if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

如果key的hash相等,且==或者equals对比的值相等,则证明key相等。
我们举个例子:

        String str1 = new String("HelloJava");
        String str2 = new String("HelloJava");
        System.out.println("str1 == str2:"+(str1 == str2));
        System.out.println("str1.equals(str2):"+str1.equals(str2));

        System.out.println("str1的hashcode:"+str1.hashCode());
        System.out.println("str2的hashcode:"+str2.hashCode());

        System.out.println("str1的Hash值:"+hash(str1.hashCode()));
        System.out.println("str2的Hash值:"+hash(str2.hashCode()));

        //输出结果如下:
        //str1 == str2:false
        //str1.equals(str2):true
        //str1的hashcode:-1094607372
        //str2的hashcode:-1094607372
        //str1的Hash值:-1269085867
        //str2的Hash值:-1269085867

可以看到,str1的hash和str2的hash是相等的,虽然==的值为false,但是equals的值为true,所以str1和str2在HashMap中依然是相等的key.

那么如果判断当前的HashMap中没有此key,就要将其key和value都添加到HashMap中,见下面这个方法:

    void addEntry(int hash, K key, V value, int bucketIndex) {

        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }

可以看到,这个方法其实就是将table[bucketIndex]下的链断开,将新的Entry插入到最前面,再将链搭起来。如下图:

除了这个还有reSize()方法,就是当tale的占用超过threshold时,table长度就会扩充两倍,具体细节下面说。

get的实现

get的实现还是依靠判断key是否相等来取值,若有,则返回其值,若没有则返回null.

public V get(Object key) {
        //如果key等于null,则直接放table数组下标为0的位置上
        if (key == null)
            return getForNullKey();
        int hash = hash(key.hashCode());
        //先定位table数组下标位置,再遍历该位置处的链表
        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.equals(k)))
                return e.value;
        }

        //没有找到,返回null
        return null;
}
null值的存取

null key总是存放在table数组的第一个元素位置,也就是table[0]。
注意:0下标不一定只存储key为null的元素

    //存值:
    private V putForNullKey(V value) {
        //将数组下标为0的元素赋值给e,然后遍历这个链表
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {

            //判断null为key的entry是否存在,若存在,替换值,返回旧值
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        //若不存在,添加至链表,返回null
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }


    //取值
    private V getForNullKey() {
        //判断数组下标为0的链表中,key为null的值是否存在,若存在返回其值
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        //若不存在,返回null
        return null;
    }
解决Hash冲突的方法

现在不予考虑细节

1. 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列)
2. 再哈希法
3. 链地址法
4. 建立一个公共溢出区

Java中hashmap的解决办法就是采用的链地址法。

用链地址法处理冲突的办法是:把具有相同散列地址的关键字(同义词)值放在同一个单链表中,称为同义词链表。

再散列reSize的过程

首先这个过程是自动的,当table的占用超过threshold(capticy*loadFactor)时,resize()方法就会自动调用,扩充table的长度。

如果当前的capacity超过了MAXIMUM_CAPACITY,就将threshold设置为Interger.MAX_VALUE,然后就不会扩容了。

具体实现看下面的源码:

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30; //2的30次方
/**
     * Rehashes the contents of this map into a new array with a
     * larger capacity.  This method is called automatically when the
     * number of keys in this map reaches its threshold.
     *
     * If current capacity is MAXIMUM_CAPACITY, this method does not
     * resize the map, but sets threshold to Integer.MAX_VALUE.
     * This has the effect of preventing future calls.
     *
     * @param newCapacity the new capacity, MUST be a power of two;
     *        must be greater than current capacity unless current
     *        capacity is MAXIMUM_CAPACITY (in which case value
     *        is irrelevant).
     */
    void resize(int newCapacity) {
        //旧table
        Entry[] oldTable = table;
        //旧table的容量
        int oldCapacity = oldTable.length;
        //如果旧table的容量==MAXIMUM_CAPACITY,将threshold设置为Integer.MAX_VALUE,返回
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }
        //按新容量大小创建newTable
        Entry[] newTable = new Entry[newCapacity];
        //数据转移
        transfer(newTable);
        table = newTable;
        //threshold重新赋值
        threshold = (int)(newCapacity * loadFactor);
    }




 /**
     * Transfers all entries from current table to newTable.
     */
    void transfer(Entry[] newTable) {
        Entry[] src = table;
        int newCapacity = newTable.length;
        //遍历原table
        for (int j = 0; j < src.length; j++) {
            Entry<K,V> e = src[j];
            if (e != null) {
                src[j] = null;
                do {
                    Entry<K,V> next = e.next;
                    //将原table的entry重新计算index,再放入到新table中
                    int i = indexFor(e.hash, newCapacity);
                    e.next = newTable[i];
                    newTable[i] = e;
                    e = next;
                } while (e != null);
            }
        }
    }
      .
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值