java 映射 putAll 覆盖还是添加?

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

Map putAll overrides or adds?

javamap

提问by Jimmy Geers

When i use the .putAll()will another .putAll()override the content of the map? Will my map contain SomeOfMyObjects and SomeOfMyObjects?

当我使用.putAll()另一个.putAll()会覆盖地图的内容吗?我的地图会包含 SomeOfMyObjects 和 SomeOfMyObjects 吗?

Map<MyObject> blah = new HashMap<>();
blah.putAll('SomeOfMyObjects')
blah.putAll('SomeOfMyObjects')

Thanks!

谢谢!

回答by Suresh Atta

If you see docs

如果你看到文档

Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map.

将所有映射从指定映射复制到此映射(可选操作)。此调用的效果等同于对指定映射中从键 k 到值 v 的每个映射在此映射上调用一次 put(k, v) 的效果。

this call is equivalent to that of calling put(k, v) 

And for as per put() method

而对于 按put()方法

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

将指定值与此映射中的指定键相关联(可选操作)。如果映射先前包含键的映射,则旧值将替换为指定值。(当且仅当 m.containsKey(k) 返回 true 时,才称映射 m 包含键 k 的映射。)

回答by rec

It behaves just like calling "put" for every Entry in the argument map, so it adds, retaining whatever is already in the map. If the same key is added again, its value is overwritten. putAll tries to optimize the bulk-add by first expanding the map internally to accommodate the new data, as to avoid intermediate resizing/rehashing operations.

它的行为就像为参数映射中的每个条目调用“放置”一样,因此它会添加,保留映射中已经存在的任何内容。如果再次添加相同的键,其值将被覆盖。putAll 尝试通过首先在内部扩展地图以容纳新数据来优化批量添加,以避免中间调整大小/重新散列操作。

回答by AitorTheRed

According to the documentation: http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#putAll(java.util.Map)It just adds the maps, not override the content.

根据文档:http: //docs.oracle.com/javase/6/docs/api/java/util/Map.html#putAll(java.util.Map)它只是添加地图,而不是覆盖内容。