Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - 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!

question from:https://stackoverflow.com/questions/934775/changing-value-after-its-placed-in-hashmap-changes-whats-inside-hashmap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...