Java集合-HashMap数据结构详解

HashMap源码中用到的几种运算符

>>>:右移,带符号的

^:按位异或

&:逻辑与


声明JDK的版本1.7


HashMap的存储结构是数组+链表。HashMap添加键值对的时候添加的是Entrty对象,Entrty对象保存了key,value和next(也就是Entrty)对象。其中Entrty类是HashMap的内部类。


HashMap put一个键值对的时候的源码流程:

put函数大致的思路为:

  1. 对key的hashCode()做hash,然后再计算index;
  2. 如果没碰撞直接放到bucket里;
  3. 如果碰撞了,以链表的形式存在buckets后;
  4. 如果碰撞导致链表过长(大于等于TREEIFY_THRESHOLD),就把链表转换成红黑树;//这个好像是jdk1.8里的
  5. 如果节点已经存在就替换old value(保证key的唯一性)
  6. 如果bucket满了(超过load factor*current capacity),就要resize。

    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value); //如果key为null
        int hash = hash(key);//获取key的hash值
        int i = indexFor(hash, table.length);//根据hash值获取存储的索引
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {//根据i,找到当前链表并且遍历
            Object k;
                       // hash值相等并且key也想等,则认为是同一个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;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);//如果key不相等,则把新的Entrty对象添加至数组中
        return null;
    }

重点来看addEntrty方法:

    void addEntry(int hash, K key, V value, int bucketIndex) {
        //如果容量不够,就根据loadFactor扩大数组容量到原来的1.5倍和ArrayList一样,同时根据数组长度重新计算hash和index值
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        //创建新的Entrty对象并添加至数组中
        createEntry(hash, key, value, bucketIndex);
    }

   //如果该位置有元素,则当前Entrty的next指向它,否则为空
  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++;
  }

每次put一个元素到HashMap中,都new一个Node对象,位置是通过计算key的hash值来确定。如果两个元素有相同的hash值,它们会被放在同一个索引上。原来它是以链表(LinkedList)的形式来存储的。上面已经详细讲过了!!!


//key的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();

        // 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值,得到的索引也有可能是相同的。

    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);
    }

HashMap get的源码流程:

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
关键是看getentrty()方法:

    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);//这里同样是用key获取hash值,并找到相应的index位置
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            //hash值相等,并且key也相等,就返回Entrty对象,否则返回null。完美的回答!!!
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心所向皆可成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值