在 Java 中向 HashMap 添加空键或值有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2945309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:47:02  来源:igfitidea点击:

What is the use of adding a null key or value to a HashMap in Java?

javanullhashmapkey

提问by subhashis

HashMap allows one null key and any number of null values. What is the use of it?

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

采纳答案by Michael Mrozek

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);

HashMaphandles 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

HashMap专门处理空键(因为它不能调用.hashCode()空对象),但空值没什么特别的,它们像其他任何东西一样存储在地图中

回答by tony

One example would be for modeling trees. If you are using a HashMap to represent a tree structure, where the key is the parent and the value is list of children, then the values for the nullkey would be the root nodes.

一个例子是为树建模。如果您使用 HashMap 来表示树结构,其中键是父节点,值是子null节点列表,则键的值将是根节点。

回答by aroth

Here's my only-somewhat-contrived example of a case where the nullkey can be useful:

这是我唯一有点做作的示例,说明null密钥可能有用:

public class Timer {
    private static final Logger LOG = Logger.getLogger(Timer.class);
    private static final Map<String, Long> START_TIMES = new HashMap<String, Long>();

    public static synchronized void start() {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(null)) {
            LOG.warn("Anonymous timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(null).longValue()) +"ms"); 
        }
        START_TIMES.put(null, now);
    }

    public static synchronized long stop() {
        if (! START_TIMES.containsKey(null)) {
            return 0;
        }

        return printTimer("Anonymous", START_TIMES.remove(null), System.currentTimeMillis());
    }

    public static synchronized void start(String name) {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(name)) {
            LOG.warn(name + " timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(name).longValue()) +"ms"); 
        }
        START_TIMES.put(name, now);
    }

    public static synchronized long stop(String name) {
        if (! START_TIMES.containsKey(name)) {
            return 0;
        }

        return printTimer(name, START_TIMES.remove(name), System.currentTimeMillis());
    }

    private static long printTimer(String name, long start, long end) {
        LOG.info(name + " timer ran for " + (end - start) + "ms");
        return end - start;
    }
}

回答by Anthone

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

另一个例子:我用它按日期对数据进行分组。但有些数据没有日期。我可以将它与标题“NoDate”分组

回答by Eborbob

The answers so far only consider the worth of have a nullkey, but the question also asks about any number of null values.

到目前为止的答案只考虑了null密钥的价值,但问题还询问了any number of null values.

The benefit of storing the value nullagainst a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

null在 HashMap 中针对键存储值的好处与在数据库等中相同 - 您可以记录具有空值(例如字符串“”)和根本没有值(空)之间的区别.

回答by Zorac

One example of usage for nullvaluesis when using a HashMapas a cache for results of an expensive operation (such as a call to an external web service) which may return null.

使用null值的一个例子是,当使用 aHashMap作为可能返回null.

Putting a nullvalue in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey)returns false), and where the operation has been performed but returned a nullvalue (cache.containsKey(someKey)returns true, cache.get(someKey)returns null).

null在映射中放置一个值可以让您区分未对给定键执行操作(cache.containsKey(someKey)returns false)的情况,以及已执行操作但返回null值的情况(cache.containsKey(someKey)returns truecache.get(someKey)returns null)。

Without nullvalues, you would have to either put some special value in the cache to indicate a nullresponse, or simply not cache that response at all and perform the operation every time.

如果没有null值,您将不得不在缓存中放置一些特殊值来指示null响应,或者根本不缓存该响应并每次都执行操作。

回答by Gunnar

A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

当映射存储 UI 选择的数据时,空键也很有用,其中映射键代表 bean 字段。

A corresponding null field value would for example be represented as "(please select)" in the UI selection.

例如,相应的空字段值将在 UI 选择中表示为“(请选择)”。