JDK 方法中的小坑

JDK 方法中的小坑

Map.getOrDefault

如果key对应的value本身为空而不是不存在这个key,那么getOrDefault会返回null

    # 如果key对应的value本身为空而不是不存在这个key,那么getOrDefault会返回null
    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }
    
     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;
    }
测试
HashMap<String, String> map = new HashMap<>();
map.put("huakai",null);
System.out.println("mapValue=" + map.getOrDefault("huakai", "default"));
结果
mapValue=null

相关推荐

  1. JDK 方法

    2024-07-17 23:10:03       21 阅读
  2. Oracle JDK 8 computeIfAbsent 方法及实践

    2024-07-17 23:10:03       43 阅读
  3. gofor range以及解决方案

    2024-07-17 23:10:03       55 阅读
  4. JDK8接口新增方法

    2024-07-17 23:10:03       57 阅读
  5. Pythonclass类和方法用法详解及常见

    2024-07-17 23:10:03       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 23:10:03       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 23:10:03       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 23:10:03       62 阅读
  4. Python语言-面向对象

    2024-07-17 23:10:03       72 阅读

热门阅读

  1. LVS集群简介

    2024-07-17 23:10:03       22 阅读
  2. 类和对象-多态-纯虚函数和抽象类

    2024-07-17 23:10:03       21 阅读
  3. 建筑产业网元宇宙的探索与实践

    2024-07-17 23:10:03       21 阅读
  4. 微信小程序加载动画文件

    2024-07-17 23:10:03       29 阅读
  5. 刷题记录:LeetCode 925.长按键入

    2024-07-17 23:10:03       24 阅读
  6. 实际项目中JVM调优

    2024-07-17 23:10:03       20 阅读
  7. 如何做到思维的顺畅运行

    2024-07-17 23:10:03       20 阅读
  8. Linux下Supervisor的安装与配置

    2024-07-17 23:10:03       19 阅读