繁体   English   中英

HashMap允许重复?

[英]HashMap allows duplicates?

我对HashMap有疑问,因为我们都知道HashMap允许一个空键和值对,我的问题是

如果我这样写,

m.put(null,null);
m.put(null,a);

它会抛出(错误或异常)还是会覆盖该值或者什么是returing的值?

Hashmap类型如果hashmap键是相同的键,则覆盖该键

map.put("1","1111");
map.put("1","2222");

产量

key:value
1:2222

HashMap中的每个都必须是唯一的。

当“添加重复键”时,旧值(对于相同的键,因为键必须是唯一的)被简单地替换; HashMap.put

将指定的值与此映射中的指定键相关联。 如果映射先前包含键的映射, 则替换旧值

返回与key关联的先前值 ,如果没有key的映射,则返回 null。

就null而言:允许使用单个null (因为键必须是唯一的),但HashMap可以具有任意数量的空 ,而null键不需要具有空值。 根据文件

[.. HashMap]允许空和[a] null

但是,文档中没有说明null / null需要是特定的键/值对或null /“a”无效。

在这个意义上不允许重复,它允许添加你,但它不关心这个键已经有一个值。 所以目前一键只有一个值

它会静默覆盖null键的value 没有例外。

当您尝试获取时,最后插入的值为null将返回。

这不仅是null和任何键。

有一个简单的例子

   Map m = new HashMap<String, String>();
   m.put("1", "a");
   m.put("1", "b");  //no exception
   System.out.println(m.get("1")); //b

代码示例:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

输出:

{null=a}

它会覆盖键null的值

HashMap不允许重复键,但由于它不是线程安全的,因此可能会出现重复键。 例如:

 while (true) {
            final HashMap<Object, Object> map = new HashMap<Object, Object>(2);
            map.put("runTimeType", 1);
            map.put("title", 2);
            map.put("params", 3);
            final AtomicInteger invokeCounter = new AtomicInteger();

            for (int i = 0; i < 100; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        map.put("formType", invokeCounter.incrementAndGet());
                    }
                }).start();
            }
            while (invokeCounter.intValue() != 100) {
                Thread.sleep(10);
            }
            if (map.size() > 4) {
// this means you insert two or more formType key to the map
               System.out.println( JSONObject.fromObject(map));
            }
        }
m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

hashmap中不允许重复键。
但是,价值可以重复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM