我有一個HashMap,我寫了一個類來處理添加和檢索值。java java HashMap.putall clone所有元素?
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
這意味着我適用於矩陣1是反射到矩陣2的每一個變化。 我幾乎可以肯定putAll會創建副本。我究竟做錯了什麼?
'.putAll()'從來不「深副本」;它只做淺拷貝。你從哪裏讀到它的深度拷貝? – fge
put和putall只是存儲對象的引用。 – Dan
也許我錯了。因此,我可以克隆Hashmap的唯一方法是如果我遍歷所有密鑰並克隆數組? – user1378063