This post will discuss how to create a copy of a 2-dimensional array in Java with dynamic column size.

1. Using clone() method

A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

Download  Run Code

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12]]

 
The code can be further shortned to:

Download  Run Code

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12]]

2. Using System.arraycopy() method

You can also use the System.arraycopy() method to copy an array from the specified source array, beginning at the specified position, to the specified position of the destination array. This is demonstrated below:

Download  Run Code

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12]]

3. Using Arrays.copyOf() method

Another alternative is to use the Arrays.copyOf() method to create a complete copy of an array. The following solution uses a for loop to iterate over each row of the original array and then calls the Arrays.copyOf() method to copy each row.

Download  Run Code

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12]]

4. Naive solution

You can write your own routine to copy the 2-dimensional array using nested loops, as shown below. However, the solution does not work when the column size isn’t fixed. Note that all the above solutions work even when the column size is not fixed.

Download  Run Code

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [10, 11, 12, 0, 0]]

That’s all about creating a copy of a 2-dimensional array in Java.