'Copy a 2D array with some of the values null
I've added java.util.Arrays to deep print easily at the end (for this example), but I cant use it to copy the array
I need to copy this 2D array, but I just cant seem to figure out how to replace the inner array I create with just null. I have the main commented for what I need to do.
I create an array the size of the original array, but it places 3 null values in the inner loop because I initialize the array that way, but I dont know how else I could initialize the array, and have it be the same length.
import java.util.Arrays;
public class makeCopyOfArray {
public static String[][] copyArray() {
String[][] array = new String[][] {{"1", "1", "1"}, {"2", "2", "2"}, null, null, null};
String[][] arrayCopy = new String[array.length][array[1].length];
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
continue;
}
for (int j = 0; j < array[i].length; j++) {
arrayCopy[i][j] = array[i][j];
}
}
return arrayCopy;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(copyArray()));
// prints out
// [[1, 1, 1], [2, 2, 2], [null, null, null], [null, null, null], [null, null, null]]
// need it to print out
// [[1, 1, 1], [2, 2, 2], null, null, null]
}
}
Solution 1:[1]
I figured it out. I just created a copy of the array that was filled with null.
import java.util.Arrays;
public class makeCopyOfArray {
public static String[][] copyArray() {
String[][] array = new String[][] {{"1", "1", "1"}, {"2", "2", "2"}, null, null, null};
String[][] arrayCopy = new String[array.length][]; //create an array with just empty null
//loop through array and copy to arrayCopy the inner lists that are not null.
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
arrayCopy[i] = array[i];
}
}
return arrayCopy;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(copyArray()));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dftag |
