将值放入 HashMap 后更改值会更改 HashMap 中的内容? [英] Changing value after it's placed in HashMap changes what's inside HashMap?

查看:60
本文介绍了将值放入 HashMap 后更改值会更改 HashMap 中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个新的 HashMap 和一个新的 List,然后使用任意键将 List 放在 Hashmap 中,然后再调用 List.clear() 会影响我放置的内容在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?

这里更深层次的问题是:当我向 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?

谢谢!

推荐答案

这里发生的情况是您将 指针 放置到哈希图中的列表,而不是列表本身.

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

当你定义时

List<SomeType> list;

您定义的是指向列表的指针,而不是列表本身.

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

当你这样做时

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.

请参阅 http://javadude.com/articles/passbyvalue.htm 了解详情Java 中的按值传递.

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

这篇关于将值放入 HashMap 后更改值会更改 HashMap 中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆