Java: Move null values to the right of all non-null elements in 2D array using for loops only

Viewed 29

Given String[] [] arr2D = [["sun", "moon"], null, ["black", "white"], ["dog", "cat"], null], how can I loop through arr2D to shift the first null to the immediate right of ["dog", "cat"] or to the end of the array so that arr2D becomes [["sun", "moon"], ["black", "white"], ["dog", "cat"], null, null]?

I have tried adapting this example involving 1D arrays but I ended up with a nullPointerException every time.

// I'm hardcoding i < 4 because there are 4 elements between and including ["sun", "moon"] and ["dog", "cat"]
for(int i = 0; i < 4; i++) {
  if(arr2D[i] == null) {
    for(int j = i + 1; j < 4; j++) {
      arr2D[j - 1][0] = arr2D[j][0];
      arr2D[j- 1][1] = arr2D[j][1];
    }
    arr2D[4 - 1] = null;
    break;
  }
}

Exception in thread "main" java.lang.NullPointerException: Cannot store to object array because "items[...]" is null

1 Answers

The easiest solution using only loops would be to create a new array and copy the non null values:

static String[][] moveNullsRight(String[][] arr){
    String[][] result = new String[arr.length][];
    for (int i = 0, j = 0; i < arr.length; i++){
        if (arr[i] != null){
            result[j++] = arr[i];
        }
    }
    return result;
}

If you need to sort your array in place use something like below:

static String[][] moveNullsRight(String[][] arr){
    for(int i = 0; i < arr.length - 1; i++){
        int m = i;
        for(int j = i+1; j < arr.length; j++){
            if(arr[m] == null && arr[j] != null){
                m = j;
            }
        }
        String[] temp = arr[m];
        arr[m] = arr[i];
        arr[i] = temp;
    }
    return arr;
}
Related