Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map putAll overrides or adds?

Tags:

java

map

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

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

Thanks!

like image 521
Jimmy Geers Avatar asked Jul 24 '13 07:07

Jimmy Geers


People also ask

Does map putAll overwrite?

So with this definition, it overrides existing keys with new values. Whether the documentation changed or not, putAll will put All.

How does HashMap putAll work?

HashMap. putAll() is an inbuilt method of HashMap class that is used for the copy operation. The method copies all of the elements i.e., the mappings, from one map into another. Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from.

How can I combine two HashMap objects containing the different types?

Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example. You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.


2 Answers

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.

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

And for as per put() method

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

like image 70
Suresh Atta Avatar answered Nov 15 '22 21:11

Suresh Atta


Not sure if anyone else finds the advice above opposing. But as a new Jenkins/Groovy user, I had to test it for myself to validate and can confirm it overwrites for "put" and "putAll".

        LinkedHashMap test = [X: 1]
        test.put("X", 2)
        assertTrue(test["X"] == 2)

and

        LinkedHashMap test = [X: 1]
        LinkedHashMap test2 = [X: 2]
        test.putAll(test2)
        assertTrue(test["X"] == 2)   
like image 25
James Joyce Avatar answered Nov 15 '22 20:11

James Joyce