本文介绍了在 Java 中向 HashMap 添加空键或值有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap 允许一个空键和任意数量的空值.有什么用?
HashMap allows one null key and any number of null values. What is the use of it?
推荐答案
我不是很肯定你在问什么,但如果你正在寻找一个何时想要使用空键的例子,我用它们通常在映射中表示默认情况(即如果给定键不存在则应使用的值):
I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):
Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);
HashMap
专门处理空键(因为它不能在空对象上调用 .hashCode()
),但空值没什么特别的,它们'像其他任何东西一样重新存储在地图中
HashMap
handles null keys specially (since it can't call .hashCode()
on a null object), but null values aren't anything special, they're stored in the map like anything else
这篇关于在 Java 中向 HashMap 添加空键或值有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!