gpt4 book ai didi

java - java HashMap.putall 克隆所有元素吗?

转载 作者:搜寻专家 更新时间:2023-11-01 02:07:11 26 4
gpt4 key购买 nike

我有一个 Hashmap,我在其中编写了一个处理添加和检索值的类。

class ReputationMatrix
{
private HashMap < Integer, int[] > repMatrix;

public ReputationMatrix()
{
repMatrix = new HashMap < Integer, int[] > ();
}

public void addrating(int nodeId, boolean rating)
{
int[] alphaBeta;

if (repMatrix.containsKey(nodeId))
{
alphaBeta = repMatrix.get(nodeId);

if (rating == true)
{
alphaBeta[0] = alphaBeta[0] + 1;
}
else
{
alphaBeta[1] = alphaBeta[1] + 1;
}

repMatrix.put(nodeId, alphaBeta);
}
else
{
alphaBeta = new int[2];

if (rating == true)
{
alphaBeta[0] = 2;
alphaBeta[1] = 1;
}
else
{
alphaBeta[0] = 1;
alphaBeta[1] = 2;
}

repMatrix.put(nodeId, alphaBeta);

}
}

public int[] getNodeIds()
{
int[] nodeIds = new int[repMatrix.size()];
int index = 0;

for (int key: repMatrix.keySet())
{
nodeIds[index] = key;
index++;
}

return nodeIds;
}

public int getAlpha(int nodeId)
{
return repMatrix.get(nodeId)[0];
}

public int getBeta(int nodeId)
{
return repMatrix.get(nodeId)[1];
}

public ReputationMatrix clone()
{
ReputationMatrix matrixClone = new ReputationMatrix();
matrixClone.repMatrix.putAll(this.repMatrix);
return matrixClone;
}
}

我实现了一个克隆方法来简单地返回一个完全独立于原始的 ReputationMatrix 的单独副本。

我测试了这样的代码:

public class Main
{
/**
* @param args
*/
public static void main(String[] args)
{
ReputationMatrix matrix1 = new ReputationMatrix();
matrix1.addrating(18, true);

ReputationMatrix matrix2 = matrix1.clone();

System.out.println(matrix1.getAlpha(18));
System.out.println(matrix2.getAlpha(18));

matrix1.addrating(18, true);

System.out.println(matrix1.getAlpha(18));
System.out.println(matrix2.getAlpha(18));
}
}

输出是:

2
2
3
3

这意味着我对 matrix1 应用的每个更改都会反射(reflect)到 matrix2 上。我几乎可以肯定 putAll 确实会创建副本。我做错了什么?

最佳答案

来自documentation :

putAll

Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map.

因此它不会复制对象,它只会添加从原始 map 到新 map 的映射。

要执行您想要的操作,您需要显式复制每个值:

Map<Integer, int[]> originalMatrix = new HashMap<>();
int[] original = {1, 2, 3};
originalMatrix.put(1, original);
Map<Integer, int[]> newMatrix = new HashMap<>();

for (Map.Entry<Integer, int[]> entry : originalMatrix.entrySet()) {
newMatrix.put(entry.getKey(), entry.getValue().clone());
}

Arrays.fill(original, 0);

System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(newMatrix.get(1)));

输出:

[0, 0, 0]
[1, 2, 3]

关于java - java HashMap.putall 克隆所有元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com