0

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

2
  • If you edit your post to include what you've tried and the stack trace from the NPE we can more easily help you fix your your homework assignment. As it is you are asking people to jump through hoops in order to help you. Commented Sep 14, 2022 at 18:37
  • Apologies, check the post again Commented Sep 14, 2022 at 18:46

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I should have been more specific; while Comparator.nullsLast looks very helpful, I was looking for a solution that only uses for loops. Perhaps I could view the source code of nullsLast
Apologies, check the post again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.