繁体   English   中英

Java:仅使用 for 循环将 null 值移动到二维数组中所有非空元素的右侧

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

给定String[] [] arr2D = [["sun", "moon"], null, ["black", "white"], ["dog", "cat"], null] ,我如何循环arr2D将第一个null移动到["dog", "cat"]的右侧或数组的末尾,以便arr2D变为[["sun", "moon"], ["black", "white"], ["dog", "cat"], null, null]

我已经尝试调整这个涉及 1D arrays 的示例,但我每次都以nullPointerException告终。

// 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

仅使用循环的最简单解决方案是创建一个新数组并复制非 null 值:

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;
}

如果您需要对数组进行排序,请使用以下内容:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM