因此,我尝试遍历并将一组坐标存储在具有整数键的哈希图中。但是,哈希图似乎是将最后一对坐标映射到每个键,以便当我遍历并在末尾获得每一对时,它们都是相同的。下面的代码,任何帮助将是巨大的!谢谢!
public HashMap<Integer,int[]> tiles;
public Board()
{
setPreferredSize(new Dimension(600, 600));
tiles = new HashMap<Integer,int[]>();
setTiles();
}
public void setTiles() {
int[] coords = { 525, 525 };
Integer square;
for (square=1;square<=9;square++) {
System.out.println(square+": "+coords[0]+",, "+coords[1]);
tiles.put(square,coords);
int[] coord = tiles.get(square);
System.out.println(square+": "+coord[0]+"; "+coord[1]);
coords[0] = coords[0] - 50;
}
tiles.put(square,coords);
for (square=11;square<=19;square++) {
System.out.println(square+": "+coords[0]+",, "+coords[1]);
tiles.put(square,coords);
int[] coord = tiles.get(square);
System.out.println(square+": "+coord[0]+"; "+coord[1]);
coords[1] = coords[1] - 50;
}
tiles.put(square,coords);
for (square=21;square<=29;square++) {
System.out.println(square+": "+coords[0]+",, "+coords[1]);
tiles.put(square,coords);
int[] coord = tiles.get(square);
System.out.println(square+": "+coord[0]+"; "+coord[1]);
coords[0] = coords[0] + 50;
}
tiles.put(square,coords);
for (square=31;square<=39;square++) {
System.out.println(square+": "+coords[0]+",, "+coords[1]);
tiles.put(square,coords);
int[] coord = tiles.get(square);
System.out.println(square+": "+coord[0]+"; "+coord[1]);
coords[1] = coords[1] + 50;
}
tiles.put(square,coords);
for (square = 1;square<=40;square++) {
int[] coord = tiles.get(square);
System.out.println(square+": "+coord[0]+"/ "+coord[1]);
}
}
最佳答案
您正在为所有键重用同一数组实例。最好每次put
数组的副本。例如:
tiles.put(square, Arrays.copyOf(coords, 2));
代替
tiles.put(square, coords);
关于java - Java HashMap覆盖先前的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29286499/