HashMap 源码分析

(1)getEntry(Object key) 方法:

final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        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;
    }

根据key的hash值计算出索引,得到table中的位置,然后遍历table处的链表

for(Entry<k,v> e = table[indexFor(hash, table.length)]; e!=null; e=e.next())

对比e的hash,并且判断k是否相等(== || equals)
这是因为即使具有相同的hash值,也不能代表两个完全相等
需要采用equals进行判断

(2)put(K key, V value) 方法

 public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        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;
            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;
    }

步骤:
hash(key.hashcode())->table[indexFor(hash, table.length)]->loop the linkedlist
->(has the key)cover the value
->(not foud key)addEntry

(3)addEntry

(4)hash()方法

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

通过Key的hashcode()方法得值再加hash计算得出

(5)map中比较类的equals和hashcode关系
重写equals方法,一定要重写hashcode,要确保如果equals相等,hashcode要一致,因为关系到indexFor在table下的数组位置
但是如果equals不相等,hashcode也可能相等,这就是会造成冲突

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值