【问题标题】:Adding list1 to list2 and updating list1 without affecting list2将list1添加到list2并更新list1而不影响list2
【发布时间】:2019-04-05 09:54:29
【问题描述】:

我正在开发一款棋盘游戏,目前正在尝试将所有周围的邻居保存为 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()}}}}

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

【问题讨论】:

    标签: java list nested-lists


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2021-09-10
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        相关资源
        最近更新 更多