简体   繁体   中英

Adding list1 to list2 and updating list1 without affecting list2

I'm working on a board game and currently trying to save all surrounding neighbors in a 2D array as lists in a list. The problem that I'm having is that when I have saved list1 to list2, and then move on in the iteration and change list1 to something else, it also affects list2 so I lose the values of the other neighbor.

This is what I have tried:

     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()}}}}

If my player is surrounded by two neighbors I would expect the output of the forcedPlays to look like for example: [[2,1],[4,3]], but instead it looks like [[],[]]. So what I what I don't understand is how do i add list1 to list2 and then cut the connection between them so when I clear list1 it wont clear list2?

You can create a copy of forcedPlay before adding it.

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

This way changes made to forcedPlay won't affect the list that was added to the outer list.

You're doing a reference copy. Basically list1 is pointing at some of the elements of list2. You need to add to list2 copies of elements in list1, clones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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