如果您試圖複製值並更改值的狀態,則需要創建深層副本,這需要知道如何創建Map
中保存的對象的副本作爲值。希望這個測試能說明我的意思。
@Test
public void testHashMap() throws Exception {
final Map<Integer, TestContainer<Double>> hashmap = new HashMap<Integer, TestContainer<Double>>();
final TestContainer<Double> t1 = new TestContainer<Double>(1d);
final TestContainer<Double> t2 = new TestContainer<Double>(2d);
hashmap.put(1, t1);
hashmap.put(2, t2);
// create a separate collection which can be modified
final Set<TestContainer<Double>> hashset = new HashSet<TestContainer<Double>>(hashmap.values());
assertEquals(2, hashmap.size());
assertEquals(2, hashset.size());
hashset.remove(t2);
assertEquals(2, hashmap.size());
assertEquals(1, hashset.size());
// prove that we cannot modify the contents of the collection
hashset.iterator().next().o += 1;
assertEquals(2d, t1.o, 0d);
}
private static final class TestContainer<T> {
private T o;
private TestContainer(final T o) {
this.o = o;
}
}
使用clone()或新的HashSet
@elbanco:我的意思是你在'Set' *中的每個元素上使用'clone()'。如果你只克隆'Set'本身,那麼這將不起作用。 – 2010-09-16 15:55:51
好的...午餐後我會嘗試一下。 – codea 2010-09-16 16:04:26