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

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

问题描述

如果我创建一个新的HashMap和一个新的List,然后将List放入Hashmap中,并使用一些任意的键,然后再调用 List.clear()影响我在HashMap中放置的内容?

这里的更深层的问题是:当我向HashMap添加一些东西时,是否复制并放置了一个新对象或者是否放置了原始对象的引用?



谢谢!

解决方案

这里发生的事情是,将一个指针放置在hashmap中的列表中,而不是列表本身。



定义

 列表< SomeType>列表; 

您正在定义一个指向列表的指针,而不是列表本身。



当你做的时候

  map.put(somekey,list); 

您只是存储指针的副本,而不是列表。

如果在别的地方跟着那个指针并在最后修改了这个对象,那么任何持有那个指针的人都会引用相同的修改过的对象。

>

请参阅 http://javadude.com/articles/passbyvalue .htm 获取Java中传递值的详细信息。


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!

解决方案

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.

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

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