ilomambo
ilomambo

Reputation: 8350

HashMap memory allocation is not clear

According to android's developers site it seems like the method

public V put (K key, V value)

will use the given value object as reference, while the method

public void putAll (Map<? extends K, ? extends V> map)

will copy each of the supplied map elements to a new value object.
The android source does not reveal the internals of each of these methods.

Is my understanding correct?

Upvotes: 1

Views: 1033

Answers (4)

Weibo Li
Weibo Li

Reputation: 3605

putAll just iterate the entry set of the source Map and call put (K key, V value) for each k-v pair. Nothing special. So it behaves the same as calling put many times in a for loop.

Read the code below and then you'll be clear.

public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

Edited by the OP to complete the answer:
This code proves put(key,value) will not create a new object, but use the value argument, I just tested it and watch the variables in the debugger:

    Map<String, Rect> mymap = new HashMap<String, Rect>();
    Rect r1 = new Rect(0,120,200,155);
    mymap.put("corner", r1);
    r1.offset(20, 17);
    Rect r2 = mymap.get("corner");

r1 becomes (20,137,220,172) and so is the returned value r2, proving the reference is mantained.

Upvotes: 1

Matthias
Matthias

Reputation: 837

No, it is incorrect. putAll will also copy only the references.

There would be even no clearly defined alternative, as we have in other languages like C++, where copy- and assignment-operators are very well definded. That's probably why the wording of the documentation seems a little bit unclear in this respect: It was very much worded with a typical java way of doing things in mind.

Upvotes: 0

user2670399
user2670399

Reputation: 48

Copies all of the mappings from the specified map to 'this' map. These mappings will replace any mappings that 'this' map had for any of the keys currently in the specified map. 'this' is map object with which you are calling this function.

Upvotes: 0

ddoor
ddoor

Reputation: 5963

There is no such thing as pass by reference in java:

http://javadude.com/articles/passbyvalue.htm

See this article for long discussion: Is Java "pass-by-reference" or "pass-by-value"?

When you call put, key and value are copied in. putAll is just to copy an entire map, it is like a convenience function to make it easier to copy maps.

Too see for yourself try editing the values of key and value after you call put, you will see that they don't change in the map they were copied into, only in the scope you change them in.

Basically the values are copied when passed into a function.

Upvotes: 0

Related Questions