在 Java 中从 Map 分离 Collection 的最佳方法是什么?
我从 HashMap 获取 HashSet,但我不希望我对 HashSet 的修改反映在 HashMap 值上。
做这样的事情的最好方法是什么:
HashSet<Object> hashset = new HashSet((Collection<Object>) hashmap.values());
//Something like ...
hashset.detach();
//Then i can modify the HashSet without modifying the HashMap values
编辑: 我必须修改 HashSet 中的一个元素,但我不想修改 HashMap 中的同一元素。
谢谢!!!
I obtain a HashSet from a HashMap and I don't want that my modifications on the HashSet reflect on the HashMap values.
What's the best way of doing something like this :
HashSet<Object> hashset = new HashSet((Collection<Object>) hashmap.values());
//Something like ...
hashset.detach();
//Then i can modify the HashSet without modifying the HashMap values
Edit :
I have to modify an element in the HashSet but I don't want to modify this same element in the HashMap.
Thanks!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
也就是说,我会非常小心地制作对象的副本,除非对象的所有属性都是原始/不可变类型。如果您只是将属性对象引用复制到克隆中的对象引用,那么您的“克隆”仍然可以通过更改它引用的对象来在原始对象中产生副作用。
Try this:
That said, I would be very careful about making copies of objects unless all the attributes of the object are primitive/immutable types. If you just copy an attribute object reference to an object reference in the clone then your 'clone' can still produce side-effects in the original object by changing the objects it references.
如果您尝试复制值并更改值的状态,则需要创建深层复制,这依赖于了解如何创建
Map
中保存的对象的副本作为值。希望这个测试能够说明我的意思。If you are trying to copy the values, and change the state of the values you need to create a deep copy, which relies on knowing how to create copies of the objects held in the
Map
as values. Hopefuly this test illustrates what I mean.你很接近:
You are close:
当您像这样从
hashMap.values()
创建HashSet
时,它就已经“分离”了,因为修改HashSet
不会影响它所构建的地图。但是,如果您修改集合内的对象(例如调用其 setter),那么这些更改也将反映在
HashMap
内部(因为>Set
和Map
将引用同一个对象)。解决这个问题的一种方法是为每个元素制作 防御副本(使用
clone()
或使用复制构造函数)。另一种方法是使用不可变对象。
When you create the
HashSet
fromhashMap.values()
like this, then it's already "detached" in the sense that modifying theHashSet
will not influence the map it was constructed from.However, if you modify an object inside the set (for example calling a setter on it), then those changes will be reflected inside the
HashMap
as well (since theSet
and theMap
will refer to the same object).One way around this is to make defensive copies of each element (using
clone()
or by using a copy constructor).Another way is to use immutable objects.
如果您根据代码片段的第一行创建一个新
HashSet
,那么它已经是一个单独的集合。从集合中添加或删除项目不会更改您的hashMap
。当然,修改现有项目会 - 但那是另一回事,并且几乎总是一件非常糟糕的事情(假设您的修改影响对象平等)。If you're creating a new
HashSet
as per the first line of your code snippet, that's already a separate collection. Adding or removing items from the set won't change yourhashMap
. Modifying the existing items will, of course - but that's a different matter, and will almost always be a Very Bad Thing (assuming your modifications affect object equality).