Copy Two Dimensional ArrayList as new

前端 未结 4 1185
慢半拍i
慢半拍i 2020-12-21 08:42

So the issue I\'m having is after copying the 2d arraylist, changing the element from one 2d arraylist affects the other 2d arraylist. I want them to be completely separate

4条回答
  •  粉色の甜心
    2020-12-21 09:09

    This is what is happening in the 1D array list case, in terms of references:

    This is what is happening in the 2D array list case:

    This means that when you copy an array list using this:

    new ArrayList<>(someOldArrayList)
    

    the items themselves don't get copied, only a new array list object is created, referring to all the items in the old array list.

    In the second case, you are only changing what array list 2's items are, but index 1 of first list and second list refers to the same array list 2.

    To fix this, you need to copy the array lists inside first list and second list as well. One way to do this:

    secondList = new ArrayList<>(firstList.stream().map(x -> new ArrayList<>(x)).collect(Collectors.toList()));
    

提交回复
热议问题