Removing rows containing null from a 2D array without using ArrayList java
Solution 1:
You can maintain a 1 dimensional boolean array whose true value at index i signifies that a null is present in row i of table. Along with that, you can maintain a counter that keeps track of number of rows that contain null values as it will help to calculate the size of resizedTable. This is the sample implementation :
public class Main2 {
public static void main(String[] args) {
String table[][] = new String[5][5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++)
if (i == j & i < 3) {
table[i][j] = null;
} else {
table[i][j] = "ij";
}
}
System.out.println("before removing nulls----");
for (String temp[] : table) {
System.out.println(Arrays.toString(temp));
}
String res[][] = deleteNull(table);
System.out.println("after removing nulls----");
for (String temp[] : res) {
System.out.println(Arrays.toString(temp));
}
}
public static String[][] deleteNull(String[][] table) {
boolean flag[] = new boolean[table.length];
int count = 0;
for (int i = 0; i < table.length; i++) {
if( table[i] == null)
{
flag[i] = true;
count++;
}
else {
for (int j = 0; j < table[i].length; j++)
if (table[i][j] == null) {
flag[i] = true;
count++;
break; // if more than 1 null, we are not bothered by that
}
}
}
String[][] resizedTable = new String[table.length - count][];
int k = 0;
for (int i = 0; i < table.length; i++) {
if (flag[i]) {
continue;
} else {
resizedTable[k] = new String[table[i].length];
for (int j = 0; j < table[i].length; j++)
resizedTable[k][j] = table[i][j];
}
k++;
}
return resizedTable;
}
}
and the output is as follows :
before removing nulls----
[null, ij, ij, ij, ij]
[ij, null, ij, ij, ij]
[ij, ij, null, ij, ij]
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
after removing nulls----
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
In case the entire row points to null : it covers for that case too :
before removing nulls----
null
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
after removing nulls----
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]
[ij, ij, ij, ij, ij]