Java中的list和map如何处理空元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9799729/
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-16 07:47:04  来源:igfitidea点击:

How null element is treated by list and map in Java

javalistmap

提问by Mohit Verma

What can be rational for below output ? null elements are treated differently by list and map.

以下输出的合理性是什么?list 和 map 对 null 元素的处理方式不同。

List<Object> hoo = new ArrayList<Object>() {
    {
        add(null);
        add(null);
    }
};

Map<Object, Object> bar = new HashMap<Object, Object>() {
    {
        put(null, null);
        put(null, null);
        put(null, null);

    }
};
System.err.println("hoo:" + hoo.size());
System.err.println("bar:" + bar.size());

Output:

输出:

hoo:2
bar:1

采纳答案by jayunit100

Concretely : Lists can have duplicate items, but maps can't have duplicate keys, which is why we can have 2 nulls in a list but only one null in a map.

具体来说:列表可以有重复的项目,但地图不能有重复的键,这就是为什么我们可以在一个列表中有 2 个空值而在一个映射中只有一个空值。

The answer to your more general question (the logic of how these interfaces behave regarding duplicates), is that there is not any one "more" or "less" logical way to implement null constraints in maps.

您更一般的问题(这些接口如何处理重复项的逻辑)的答案是,没有任何一种“更多”或“更少”的逻辑方法可以在地图中实现空约束。

Certainly, there is no universal rule : for example - Originally, java's Hashtables did notallow for null values.
But later, the HashMap implemented a different behaviour (allows null values).

当然,不存在普遍规律:例如-原来,Java的哈希表没有允许空值。
但后来,HashMap 实现了不同的行为(允许空值)。

Since the real world certainly has instances where we can have null values, but there are very few instances where we would / should have a null key, you might ask your self why you have multiple entries with a null key and null value in the same data structure - do these values actually represent anything meaningful?

由于现实世界中肯定有我们可以有空值的实例,但很少有我们会/应该有空键的实例,您可能会问自己为什么有多个带有空键和空值的条目在同一个数据结构 - 这些值实际上代表什么有意义的东西吗?

回答by Shashank Kadne

HashMapwon't allow you to store values with duplicate keys(your value null in this case). That's the reason why the size is "1" in the second case.

HashMap不允许您使用重复键存储值(在这种情况下您的值为 null)。这就是为什么在第二种情况下大小为“1”的原因。

回答by Rangi Lin

Because a Mapcan only have unique key. In this case it's a null

因为 aMap只能有唯一键。在这种情况下,它是一个null

put(null, null);
put(null, null);
put(null, null);

Previous statements are actually overwriting the value after the first call. That's why the size remain 1

先前的语句实际上是在第一次调用后覆盖该值。这就是为什么尺寸保持为 1

回答by sikander

Java documentationstates:

Java 文档指出:

If the map previously contained a mapping for the key, the old value is replaced

如果映射先前包含键的映射,则替换旧值

The bar:1is entirely correct.

bar:1是完全正确的。