簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM