Changing value after it#39;s placed in HashMap changes what#39;s inside HashMap?(将值放入 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 中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将值放入 HashMap 后更改值会更改 HashMap 中的内容


- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01