Search code examples
javamultidimensional-arraycopyerase

Replicate multidimensional array in java


In Java, how do we make a copy of a 3-D array? Thing is, when we use new_array.clone() or something of that sort, we are putting the address of the entry into the another_array, and not the actual value. Hence when i clear() old_array, new_array is empty too

private List<List<List<String>>> moves = new ArrayList<List<List<String>>>();
private List<List<List<String>>> moves1 = new ArrayList<List<List<String>>>();

.blah
.blah 
.blah

mid_array = new ArrayList<List<String>>();//will use this array to insert inot moves1

for(int f = 0; f < moves.size(); f++)//make a copy of original array.
{

    List<String> row_st = moves.get(f).get(0);
    List<String> deck_st = moves.get(f).get(1);

    mid_array.add(row_st);//current array of the Rows
    mid_array.add(deck_st);//current array of the Deck

    moves1.add(mid_array);

    System.out.println("Moves1 "+moves1);//displays the new array correctly

    mid_array.clear();//clear mid_array, NOT moves1 or moves arrays

    System.out.println("Moves1 "+moves1);//new array is now empty

}

Solution

  • In Java, Objects are always referenced so when you do:

       moves1.add(mid_array);
    

    It means mid_array is added to moves1 but still referenced with mid_array. This way, when you call mid_array.clear(), its clear from both the places.

    If you want to maintain the list inside moves1, then better to create a new instance of mid_array inside the for loop e.g. below:

     for(int f = 0; f < moves.size(); f++)//make a copy of original array.
     {
        List<List<String>> mid_array = new ArrayList<List<String>>();
        List<String> row_st = moves.get(f).get(0);
        List<String> deck_st = moves.get(f).get(1);
    
        mid_array.add(row_st);//current array of the Rows
        mid_array.add(deck_st);//current array of the Deck
    
        moves1.add(mid_array);
    
        System.out.println("Moves1 "+moves1);//displays the new array correctly
    
        //No need to clear as in each iteration, it will instantiate a new mid_array
     }