Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 254
Diego Avatar asked Jun 01 '09 13:06

Diego


People also ask

What happens if we update the key object that is in a HashMap?

When you mutate a key which is already present in the HashMap you break the HashMap .

Can you change the value in a HashMap?

You can change either the key or the value in your hashmap, but you can't change both at the same time.

What happen when we put same key with different value in HashMap?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

What happens when you put a key object in a HashMap that is already present?

What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.


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

like image 119
Scott Stanchfield Avatar answered Sep 20 '22 18:09

Scott Stanchfield