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

发布于 2024-09-03 11:00:46 字数 37 浏览 3 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

浅笑轻吟梦一曲 2024-09-10 11:00:46

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

Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);

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

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

莫言歌 2024-09-10 11:00:46

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

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 null key would be the root nodes.

猥︴琐丶欲为 2024-09-10 11:00:46

使用 null values 的一个示例是使用 HashMap 作为昂贵操作结果的缓存(例如调用外部Web 服务),可能会返回 null

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

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

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

Putting a null value 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 null value (cache.containsKey(someKey) returns true, cache.get(someKey) returns null).

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

懒猫 2024-09-10 11:00:46

到目前为止的答案只考虑了拥有 null 键的价值,但问题还询问了任意数量的 null 值

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

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

The benefit of storing the value null against 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).

给不了的爱 2024-09-10 11:00:46

这是我唯一设计的示例,其中 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;
    }
}

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

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;
    }
}
自控 2024-09-10 11:00:46

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

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"

夜血缘 2024-09-10 11:00:46

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文