Copying a multidimensional array

The handy Arrays.copyOf() function helps us to perform elegantly an array copy, when cloning is not a viable option.

The nuisance is that it is limited to monodimensional array. What if we have to copy a two (or more) dimensional array? We can still use Array.copyOf() for the actual data copy, but we have integrate it with some "by hand" coding, to allocate memory for n-1 dimensions.

I guess that showing a twelve-dimensional example would be funnier, but let see instead a mere, an more common, bidimensional array copy.
int[][] source = {
   {1,2,3,4},
   {3,4,5,6},
   {5,6,7,8},
};

int[][] destination = new int[source.length][]; // 1
for(int i = 0; i < destination.length; ++i)
   destination[i] = Arrays.copyOf(source[i], source[i].length); // 2
1. A Java bidimensional array is nothing more than an array of arrays. What we are doing here is the first step in the copy, allocating enough memory in destination to store the arrays that are going to be created in the subsequent for loop. 2. Last step, create a copy of each one-dimensional array and store it in the just allocated room in destination.

No comments:

Post a Comment