本文介绍了在Java中为HashMap添加一个空键或值有什么用处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMap允许一个空键和任意数量的空值。什么是它的用途?

解决方案

我不是积极的你问什么,但如果你正在寻找一个想要使用null键的例子,我经常在地图中使用它们来表示默认情况(即,如果给定键不存在,应该使用的值):

 地图< A,B> FOO; 
搜索;
B val = foo.containsKey(搜索)? foo.get(search):foo.get(null);

HashMap 特别处理空键(因为它无法在空对象上调用 .hashCode()),但空值没有特别之处,它们像其他任何东西一样存储在地图中


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 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添加一个空键或值有什么用处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:19