Java HashMap 覆盖以前的值

Java HashMap overwriting previous values

所以我试图遍历一组坐标并将其存储到具有整数键的哈希图中。但是,散列图似乎将最后一对坐标映射到每个键,这样当我遍历并在最后得到每一对时,它们都是相同的。代码如下,任何帮助都会很棒!谢谢!

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

您一遍又一遍地将相同的 int[] 放入 HashMap。所以最后的修改通过 HashMap.

的所有键可见

put 操作不会将值的副本放入映射中,它会放置对对象的引用。您对同一个 int[].

有很多引用

相反,在添加数组后将一个新数组分配给 square,以便对单独数组的引用 put 进入 HashMap.