简体   繁体   English

java - 从TreeMap克隆对象中删除元素不会从java中的主treemap对象中删除

[英]Removing an element from TreeMap cloned object is not removed from main treemap object in java

I read the following logic about TreeMap :我阅读了有关TreeMap的以下逻辑:

The TreeMap.clone() method returns the shallow copy of the TreeMap instance. TreeMap.clone()方法返回TreeMap实例的浅拷贝。 In the shallow copy, object B points to object A location in memory.在浅拷贝中,对象 B 指向对象 A 在内存中的位置。 In other words, both object A and B are sharing the same elements.换句话说,对象 A 和 B 共享相同的元素。 The keys and values themselves are not cloned.键和值本身不会被克隆。

Considering this correct, I made a program as per the link problem in which I removed an element from the treemap cloned object and my expectation was that this element must have been removed from main treemap object too but it didn't happen.考虑到这一点是正确的,我根据链接问题制作了一个程序,其中我从treemap对象中删除了一个元素,我的期望是这个元素也必须从主树状图对象中删除,但没有发生。 I checked the key's hashcode too for both object but it was the same.我也检查了两个对象的密钥的哈希码,但它是相同的。 Can someone please let me know, a shallow copy is something different in TreeMap or my understanding is something incorrect?有人可以让我知道,浅拷贝在 TreeMap 中有所不同还是我的理解不正确? Jdk - 1.8 JDK - 1.8

Your understanding is somewhat incorrect (from my pov..sry!:)您的理解有些不正确(来自我的 pov..sry!:)

My understanding is "key and values are same", but the cloned maps are not (same) !我的理解是“键和值相同”,但克隆的地图不(相同) And being part of a map is an information, which nor the key nor the value "knows about", but only the maps/containers... and this information is (copied &) owned by each map, after cloning.并且作为地图的一部分是一种信息,它既不是键也不是值“知道”,但只有地图/容器......并且在克隆后,这些信息由每个地图(复制和)拥有。

I would agree with your misunderstanding / observation, if you would have checked the Map.Entry<K, V> s ... (these are also unknown to the underlying keys & values).如果您检查Map.Entry<K, V> s ...(这些对于基础键和值也是未知的),我会同意您的误解/观察。

And after cloning, you/someone must ensure it, if you want the clones to be synchronized .克隆后,如果您希望克隆同步,您/某人必须确保它。


If you indeed want "two references" of the same map (the expected behavior), you "just" share/pass the reference to this map (but watch out for concurrency, "usual" Map implementations are not thread safe):如果您确实想要同一个地图的“两个引用”(预期行为),您“只是”共享/传递对此地图的引用(但要注意并发性,“通常的” Map 实现不是线程安全的):

 //not: Map<X, Y> copy = original.clone(), but:
 Map<X, Y> ref = original; // then all changes on "original" are "reflected" at "ref" ..

Under "deep copy", I'd understand, that "keys and values" (and even deeper) get cloned, too.在“深度复制”下,我明白,“键和值”(甚至更深)也会被克隆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM