Changing value after it's placed in HashMap changes what's inside HashMap?

Viewed 61130

If I create a new HashMap and a new List, and then place the List inside the Hashmap with some arbitrary key and then later call List.clear() will it affect what I've placed inside the HashMap?

The deeper question here being: When I add something to a HashMap, is a new object copied and placed or is a reference to the original object placed?

Thanks!

8 Answers

What's happening here is that you're placing a pointer to a list in the hashmap, not the list itself.

When you define

List<SomeType> list;

you're defining a pointer to a list, not a list itself.

When you do

map.put(somekey, list);

you're just storing a copy of the pointer, not the list.

If, somewhere else, you follow that pointer and modify the object at its end, anyone holding that pointer will still be referencing the same, modified object.

Please see http://javadude.com/articles/passbyvalue.htm for details on pass-by-value in Java.

Java is pass-by-reference-by-value.

Adding the list to the hash map simply adds the reference to hash map, which points to the same list. Therefore, clearing the list directly will indeed clear the list you're referencing in the hashmap.

When I add something to a HashMap, is a new object copied and placed or is a reference to the original object placed?

It is always a reference to the object. If you clear the HashMap the object will be still "live". Then the object will be destroyed by the garbage collector if no one is referencing it anymore. If you need to copy it, take a look to Object.clone() method and to the Cloneable interface

Generally you always deal with references in Java (unless you explicitly create a new object yourself with "new" [1]).

Hence it is a reference and not a full object copy you have stored in the map, and changing the list will also effect what you see when going through the map.

It's a feature, not a bug :)

[1] Puritans will include "clone()" and serialization, but for most java code "new" is the way to get objects.

Geeze people...everything in Java is pass by value. When you pass an object, the value you are passing is the object reference. Specifically, you are passing a copy of the object reference. There are no pointers in Java either, though references are similar. Get it right!

Related