从现有创建二维字符串数组,无需特定"row"



假设我有一个二维字符串数组,包含以下行:

table[0][0] = "Tom";
table[0][1] = "Baker";
table[0][2] = "TimeLord";

我面临的挑战是从数组中删除一个特定的行,用户在该行中键入任何元素。实际的两个变暗了。我的数组是从结果集中读取的。我必须在不使用ArrayLists和不使用任何外部库/api的情况下完成上述操作。

我该怎么做?(此处效率无关紧要)

如果您接受Java对二维数组的解释会更容易。

来自Java文档

在Java编程语言中,多维数组是一个数组其组件本身就是阵列。

因此,如果要移除一个特定的"行",那么您只需要移除该位置的数组。然后相应地修改阵列。

然后使用System.arraycopy执行复制操作并删除所需的行。即:

        int[][] tester={{1,2},{3,4},{5,6},{7,8}};
        int row=2;
        System.out.println(tester.length);
        System.arraycopy(tester, row+1, tester, row, tester.length-row-1);

希望这是你想要的。

编辑:最后两行将是彼此的副本。您仍然需要删除最后一行。

    int[][] tester={{1,2},{3,4},{5,6},{7,8}};
    int row=2;
    int[][] testerCopy=new int[tester.length-1][tester[0].length];
    System.out.println(tester.length);
    System.arraycopy(tester, row+1, tester, row, tester.length-row-1);
    System.arraycopy(tester, 0, testerCopy, 0, testerCopy.length);
    System.out.println(Arrays.toString(testerCopy[0]));
    System.out.println(Arrays.toString(testerCopy[1]));
    System.out.println(Arrays.toString(testerCopy[2]));
    System.out.println(testerCopy.length);

最新更新