HashMap之containsKey

20 篇文章 0 订阅

HashMap之containsKey


前提:

  • jdk1.8之前HashMap的存储方式:链表+hash
  • jdk1.8以后中HashMap的存储方式:链表+hash+红黑树算法

业务逻辑整理

  • 1,map不能为空,且hash对应的下标要存在。否则返回null
  • 2,取下标对应的对象,如果该对象的key与入参key一致,则返回该对象
  • 3,否则,获取下一个对象,如果该对象为空,返回null
  • 4,如果当前对象是树结构,则调用getTreeNode,获取是否存在
  • 5,如果不是树结构,循环对象,如果存在对象的key与入参key一致,则返回该对象
  • 6,最终返回要么有值,要么null
public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

这个代码没啥意思,还是要看getNode方法

/**
 * Implements Map.get and related methods
 * 实现了map.get及相关方法
 * @param hash hash for key 
 * 键的hash
 * @param key the key
 * 键
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //table不为空and长度大于0,hash对应的table数组下标存在,则循环对比,否则返回null
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        //hash对应的table数组下标的对象的key,与入参的key一致,则返回当前的对象
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        //如果不是,则取下一个对象
        if ((e = first.next) != null) {
        	//如果是红黑树结构,则调用getTreeNode方法体,验证是否存在
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            //否则,循环对象,如果存在一致的,则返回该对象
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值