Map集合中get不存在的key值

版权声明:创作不易,请尊重个人劳动成果.转载请注明出处.谢谢. https://blog.csdn.net/baidu_28665563/article/details/81064681

先来看下面的代码:

Map<String, String> map = new HashMap<>();
String test = map.get("test");
System.out.println(test);

输出结果:

null

从结果可以看出,HashMap集合中,获取不存在的key时并不会报异常.

在Map的实现类HashMap中有这样一段代码

 
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @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;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            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;
}

在get方法中并没有向上抛出异常,注释也说明了返回节点或者null

猜你喜欢

转载自blog.csdn.net/baidu_28665563/article/details/81064681