How to Clone a 2D Array With Different Row Sizes in Java?
Last Updated :
08 Feb, 2024
2D arrays are two-dimensional arrays. These are the simplest forms of multidimensional arrays. Java provides various methods to clone the arrays, but when dealing with 2D arrays having varying sizes, then the process becomes more difficult. Here, we will see different methods to clone 2D arrays with different row sizes in Java.
Methods to Clone a 2D Array with Different Row Sizes
There are various methods to clone 2D arrays with different row sizes. We will see some of them here:
- Using Nested Loops
- Using "System.arraycopy"
- Using Java Streams
Now let's discuss these methods one by one.
1. Using Nested Loops
We can clone 2D arrays having different row sizes by manually iterating through each element and then copying them one by one. It involves using nested loops to traverse both rows and columns in an array.
Code example:
Java
// Java Program to Clone a 2D Array with
// Different Row Sizes Using Nested Loops
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Define a 2D array with integer values
int[][] realArray
= { { 1, 2, 3, 15 }, { 14, 5 }, { 6, 17, 8, 9, 26 } };
// Clone the realArray using cloneArray method
int[][] clonedArray = cloneArray(realArray);
// Display both the real and cloned arrays
displayArray(realArray, "Real Array");
displayArray(clonedArray, "Cloned Array");
}
// Method to clone a 2D array
private static int[][] cloneArray(int[][] original)
{
// Create a new array with the same dimensions as the original
int[][] clone = new int[original.length][];
// Iterate over each row of the original array
for (int i = 0; i < original.length; i++) {
// Create a new array for each row of the clone
clone[i] = new int[original[i].length];
// Copy the elements from the original array to the clone
for (int j = 0; j < original[i].length; j++) {
clone[i][j] = original[i][j];
}
}
return clone; // Return the cloned array
}
// Method to display a 2D array
private static void displayArray(int[][] array,
String message)
{
// Print a message indicating the purpose of the array
System.out.println(message);
// Iterate over each row of the array
for (int[] row : array) {
// Iterate over each element in the row and print it
for (int element : row) {
System.out.print(element + " ");
}
// Move to the next line after printing each row
System.out.println();
}
// Print an empty line for clarity
System.out.println();
}
}
Output:
Real Array
1 2 3 15
14 5
6 17 8 9 26
Cloned Array
1 2 3 15
14 5
6 17 8 9 26
2. Using "System.arraycopy"
The "System.arraycopy" method in Java is used to copy elements from one array to another array. It considers iterating through whole array using "System.arraycopy" and then copy each row using this method.
Code example:
Java
// Java Program to Clone a 2D Array with
// Different Row Sizes Using "System.arraycopy"
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Define a 2D array with integer values
int[][] realArray
= { { 1, 2, 3, 15 }, { 14, 5 }, { 6, 17, 8, 9, 26 } };
// Clone the realArray using cloneArray method
int[][] clonedArray = cloneArray(realArray);
// Display both the real and cloned arrays
displayArray(realArray, "Real Array");
displayArray(clonedArray, "Cloned Array");
}
// Method to clone a 2D array
private static int[][] cloneArray(int[][] original)
{
// Create a new array with the same dimensions as the original
int[][] clone = new int[original.length][];
// Iterate over each row of the original array
for (int i = 0; i < original.length; i++) {
// Create a new array for each row of the clone
clone[i] = new int[original[i].length];
// Use System.arraycopy() to copy the elements from the original array to the clone
System.arraycopy(original[i], 0, clone[i], 0, original[i].length);
}
return clone; // Return the cloned array
}
// Method to display a 2D array
private static void displayArray(int[][] array,
String message)
{
// Print a message indicating the purpose of the array
System.out.println(message);
// Iterate over each row of the array
for (int[] row : array) {
// Iterate over each element in the row and print it
for (int element : row) {
System.out.print(element + " ");
}
// Move to the next line after printing each row
System.out.println();
}
// Print an empty line for clarity
System.out.println();
}
}
Output:
Real Array
1 2 3 15
14 5
6 17 8 9 26
Cloned Array
1 2 3 15
14 5
6 17 8 9 26
3. Using Java Streams
In Java 8, Streams provides functional approach to clone a 2D array with different row sizes.
Code example:
Java
// Java Program to Clone a 2D Array with
// Different Row Sizes Using Java Streams
import java.util.Arrays;
import java.util.stream.Collectors;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Define a 2D array with integer values
int[][] realArray
= { { 1, 2, 3, 15 }, { 14, 5 }, { 6, 17, 8, 9, 26 } };
// Clone the realArray using cloneArray method
int[][] clonedArray = cloneArray(realArray);
// Display both the real and cloned arrays
displayArray(realArray, "Real Array");
displayArray(clonedArray, "Cloned Array");
}
// Method to clone a 2D array
private static int[][] cloneArray(int[][] original) {
// Use Java 8 Streams to clone the array
return Arrays.stream(original)
.map(int[]::clone)
.toArray(int[][]::new);
}
// Method to display a 2D array
private static void displayArray(int[][] array,
String message)
{
// Print a message indicating the purpose of the array
System.out.println(message);
// Iterate over each row of the array
for (int[] row : array) {
// Iterate over each element in the row and print it
for (int element : row) {
System.out.print(element + " ");
}
// Move to the next line after printing each row
System.out.println();
}
// Print an empty line for clarity
System.out.println();
}
}
Output:
Real Array
1 2 3 15
14 5
6 17 8 9 26
Cloned Array
1 2 3 15
14 5
6 17 8 9 26
Similar Reads
How to Perform a 2D FFT Inplace Given a Complex 2D Array in Java? A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to the frequency and vice versa. FFT reduces the computation time required to compute a discrete Fourier Transform and improves the performance by
5 min read
How to Make a Deep Copy of Java ArrayList? The Advantage of ArrayList is it can be defined without giving a predefined size. But the disadvantage is it is more expensive to create and maintain. To have the solution for these expenses we can create a deep copy of an ArrayList. There are two types of copies that can be made the first one is a
3 min read
How to Clone a List in Java? Given a list in Java, the task is to clone this list. Example: Input: list = ["Geeks", "for", "Geeks"] Output: clonedList = ["Geeks", "for", "Geeks"] Input: list = ["GeeksForGeeks", "A Computer Science", "Portal"] Output: clonedList = ["GeeksForGeeks", "A Computer Science", "Portal"] In Java, there
9 min read
Deep Copy of 2D Array in Java In Java, performing a deep copy of a 2D array containing objects requires careful consideration to ensure independence between the original and copied arrays. By creating new instances of objects for each element in the array, developers can achieve a true deep copy, preventing unintended side effec
3 min read
Implementation of a Circular Resizable Array in Java A Circular Resizable Array is a data structure that effectively maintains a fixed-size array by enabling members to be added or withdrawn circularly. It is sometimes referred to as a circular buffer or ring buffer. This cyclical behavior is especially helpful in situations when a smooth array wrap i
4 min read
Print a 2D Array or Matrix in Java In this article, we will learn to Print 2 Dimensional Matrix. 2D-Matrix or Array is a combination of Multiple 1 Dimensional Arrays. In this article we cover different methods to print 2D Array. When we print each element of the 2D array we have to iterate each element so the minimum time complexity
4 min read
Determine the Upper Bound of a Two Dimensional Array in Java Multidimensional arrays in Java are common and can be termed as an array of arrays. Data in a two-dimensional array in Java is stored in 2D tabular form. A two-dimensional array is the simplest form of a multidimensional array. A two-dimensional array can be seen as an array of the one-dimensional a
3 min read
How to clone an ArrayList to another ArrayList in Java? The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object. Below program illustrate the Java.util.Arra
2 min read
Difference between multidimensional array in C++ and Java Prerequisites: Multidimensional array in C++, Multidimensional array in Java Multidimensional Arrays: Multidimensional arrays are a tabular representation of arrays to store multiple elements. These dimensions can be 1D arrays, 2D-arrays, etc. Multidimensional arrays are available in both C++ and Ja
4 min read
How to Implement a Generic Deep Copy Method for Multidimensional Arrays in Java? In Java, two types of copies can be made of any data structure that are Deep copy and Shallow copy. When we make a deep copy of an array, the array is assigned a new memory space, and the content is copied into the new memory space. This means that if we make changes in any of the two arrays it will
3 min read