HashMap 如何解决冲突,Android并发原理解析

博客探讨了HashMap如何处理冲突,并深入解析Android并发机制。建议Android开发者通过系统学习和大量练习来提升技能,文中推荐了阿里P7级别的Android高级教程和CodeChina开源项目资源。
摘要由CSDN通过智能技术生成
 static final int hash(Object key) {

    int h;

    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

}



解决冲突的核心逻辑代码:



Node<K,V> e; K k;

        if (p.hash == hash &&

            ((k = p.key) == key || (key != null && key.equals(k))))

            e = p;

        else if (p instanceof TreeNode)

            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

        else {

            for (int binCount = 0; ; ++binCount) {

                if ((e = p.next) == null) {

                    p.next = newNode(hash, key, value, null);

                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

                        treeifyBin(tab, hash);

                    break;

                }

                if (e.hash == hash &&

                    ((k = e.key) == key || (key != null && key.equals(k))))

                    break;

                p = e;

            }

        }

        if (e != null) { // existing mapping for key

            V oldValue = e.value;

            if (!onlyIfAbsent || oldValue == null)

                e.value = value;

            afterNodeAccess(e);

            return oldValue;

        }

这里再贴一下创建Node的代码:

Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {

    LinkedHashMap.Entry<K,V> p =

        new LinkedHashMap.Entry<K,V>(hash, key, value, e);

    linkNodeLast(p);

    return p;

}



**HashMap的扩容**



说道HashMap的扩容,我们先来看看HashMap的resize()方法。



/**

 * Initializes or doubles table size.  If null, allocates in

 * accord with initial capacity target held in field threshold.

 * Otherwise, because we are using power-of-two expansion, the

 * elements from each bin must either stay at same index, or move

 * with a power of two offset in the new table.

 *

 * @return the table

 */

final Node<K,V>[] resize()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值