gpt4 book ai didi

Java HashMap 覆盖以前的值

转载 作者:行者123 更新时间:2023-12-01 22:23:12 25 4
gpt4 key购买 nike

所以我尝试循环并将一组坐标存储到带有整数键的 HashMap 中。然而, HashMap 似乎将最后一对坐标映射到每个键,这样当我循环并在最后得到每一对坐标时,它们都是相同的。代码如下,任何帮助都会很棒!谢谢!

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]);
}
}

最佳答案

您正在为所有键重用同一个数组实例。最好每次放入数组的副本。例如:

tiles.put(square, Arrays.copyOf(coords, 2));

而不是

tiles.put(square, coords);

关于Java HashMap 覆盖以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286499/

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