将 list1 添加到 list2 并在不影响 list2 的情况下更新 list1

Adding list1 to list2 and updating list1 without affecting list2

我正在玩棋盘游戏,目前正在尝试将二维数组中的所有周围邻居保存为列表中的列表。我遇到的问题是,当我将 list1 保存到 list2,然后继续迭代并将 list1 更改为其他内容时,它也会影响 list2,因此我丢失了另一个邻居的值。

这是我试过的:

     private ArrayList<ArrayList> forcedPlays = new ArrayList<ArrayList>();
     private ArrayList<Integer> forcedPlay = new ArrayList<Integer>();   

    private void findNeighbors(){
     for (int y = -1; y <=1 ; y+=2) {
           for (int x = -1; x <= 1; x+=2) {
               if (board[myY+y][myX+x]!=null){
                   enemyY = myY+y;
                   enemyX = myX+x;
                    forcedPlay.addAll(Arrays.asList(
                                     Integer.valueOf(enemyY),
                                     Integer.valueOf(enemyX)));

     forcedPlays.add(forcedPlay);
     forcedPlay.clear()}}}}

如果我的播放器被两个邻居包围,我希望 forcedPlays 的输出看起来像例如:[[2,1],[4,3]],但它看起来像 [[], []]。所以我不明白的是如何将 list1 添加到 list2,然后切断它们之间的连接,这样当我清除 list1 时它不会清除 list2?

您正在制作参考副本。基本上 list1 指向 list2 的一些元素。您需要将 list1 中元素的副本添加到 list2,克隆。

您可以在添加之前创建 forcedPlay 的副本。

forcedPlays.add(new ArrayList<Integer>(forcedPlay));

这样对 forcedPlay 所做的更改不会影响添加到外部列表的列表。