如果您试图复制值并更改值的状态,则需要创建深层副本,这需要知道如何创建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