使用 getOrDefault 方法,如果 key 存在但 value 为 null,则会返回默认值。

以下是一个示例:

Map<String, String> map = new HashMap<>();
map.put('key', null);

String value = map.getOrDefault('key', 'default');
System.out.println(value); // 输出:default

在上面的示例中,将 null 值放入 map 中,然后使用 getOrDefault 方法获取 key 对应的值。由于 value 为 null,所以 getOrDefault 方法返回了默认值 'default'。

Java Map 中 key 存在但 value 为 null,使用 getOrDefault 返回什么?

原文地址: https://www.cveoy.top/t/topic/m0Yc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录