I have a static Hashmap, A. I am making a copy of it, B, for calculations. When I delete elements from B and print A, those elements are gone from A too. Is this expected?
Static Map<String, ArrayList<String>> A;
private void calculate(String id) {
Map<String, ArrayList<String>> B= A;
String maxKey = getMaxKey(B);
int neighbour_matrix_length = B.size();
for(int i=0 ; i< neighbour_matrix_length; i++){
// remove all the visited nodes
ArrayList<String> visited = copy_neighbours_reachability_map.get(maxKey);
for(int j = 0; j< visited.size() ; j++)
{
String temp = visited.get(i);
Iterator<Entry<String, ArrayList<String>>> iter = B.entrySet().iterator();
// iterate through the hashmap to remove elements
while (iter.hasNext()) {
Entry<String, ArrayList<String>> entry = iter.next();
if(entry.getValue().contains(temp)){
entry.getValue().remove(temp);
}
}
}
}
// Elements from A are also getting deleted..
System.out.println("neighbours_reachability_map is ");
for (String key : A.keySet())
{
System.out.println( "Key : " + key + " - " + A.get(key).toString());
}
}
Am I missing something? I do not want elements from A to be deleted.
答案 0 :(得分:4)
您正在做的只是共享对同一对象的引用,因此更改一个将改变另一个对象。这样做:
Map<String, ArrayList<String>> B = new HashMap<>(A);
将制作地图的副本,但是......地图中的值是列表,两个地图将保留对相同列表的引用(即使新旧地图是不同的对象)。所以你还需要复制列表:
Map<String, ArrayList<String>> B = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> e : A.entrySet()) {
B.put(e.getKey(), new ArrayList<String>(e.getValue()));
}
我们在这里做的是创建对象的深层复制,因此不会共享任何引用。
答案 1 :(得分:3)
我正在制作它的副本B,用于计算。当我从B中删除元素并打印A时,这些元素也从A中删除。这是预期的吗?
是您预期的行为,因为当您说Map<String, ArrayList<String>> B= A;
时,B
会将相同 Map
称为A
(也就是说,B == A
,这意味着它们共享相同的引用)。您可以使用类似
A
复制到B
Map<String, ArrayList<String>> B = new HashMap<>(A);