繁体   English   中英

将list1添加到list2并更新list1而不影响list2

[英]Adding list1 to list2 and updating list1 without affecting list2

我正在做一个棋盘游戏,目前正在尝试将2D数组中的所有周围邻居保存为列表中的列表。 我遇到的问题是,当我将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()}}}}

如果我的玩家被两个邻居包围,那么我可以期望forcePlays的输出看起来像:[[2,1],[4,3]],但是看起来却像[[],[]]。 所以我不明白的是如何将list1添加到list2,然后断开它们之间的连接,所以当我清除list1时,不会清除list2吗?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM