【问题标题】:Returning the list of list converted to an array, excluding any null items返回转换为数组的列表列表,不包括任何空项
【发布时间】:2021-07-30 07:44:37
【问题描述】:

发现很难返回转换为数组的列表列表,不包括任何空项。项目应该按照它们在列表中出现的顺序出现。我的测试通过,直到行:
assertEquals("[-1, -2, -1, 4, 5, 6, 7, 8, 9, 100, 200, 700, 900, 10, 20, 90, 20, 22]", Arrays.toString(result ));我想知道是什么问题。

public static int[] nonNullItemsToArray(ArrayList<ArrayList<Integer>> list) {
    if (list == null) {
        return null;
    }
    int arrayLength = 0;
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) != null) {
            arrayLength += list.get(i).size();
        }
    }
    int j = 0;
    int[] alist = new int[arrayLength];
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) != null) {
            for (int k = 0; k < list.get(i).size(); k++) {
                if (list.get(i).get(k) != null) {
                    alist[j++] = list.get(i).get(k);
                }
            }
        }
    }

    return alist;
}

@Test @Graded(description="NonNullItemsToArrayComprehensive")
    public void testNonNullItemsToArrayComprehensive() {
        testNonNullItemsToArrayBasic();
        int[] result = ListOfListService.nonNullItemsToArray(null);
        assertEquals(null, result);

        result = ListOfListService.nonNullItemsToArray(list4_nullItems);
        assertEquals("[-1, -2, -1, 4, 5, 6, 7, 8, 9, 100, 200, 700, 900, 10, 20, 90, 20, 22]", Arrays.toString(result));
        currentMethodName = new Throwable().getStackTrace()[0].getMethodName();
    }

【问题讨论】:

  • 为什么/如何测试失败? (错误结果/异常)您传递的输入是什么(list4_nullItems 的内容)?
  • 在这一行失败了 assertEquals("[-1, -2, -1, 4, 5, 6, 7, 8, 9, 100, 200, 700, 900, 10, 20 , 90, 20, 22]", Arrays.toString(result));
  • 你的函数会返回什么结果?

标签: java arraylist sub-array


【解决方案1】:

正如 his/her answer 中已经提到的 saka,您的代码会在结果数组中生成不需要的 0 条目,特别是输入嵌套列表中的每个 null 条目对应一个 0 条目。

input  = [[1, 2, null], null, [null, 3, 4]]
           entry 1 ^     entry 2 ^

output = [1, 2, 3, 4, 0, 0]
       in the result  ^  ^

根本原因是您在计算初始数组大小时没有考虑这些嵌套的null 条目。

int arrayLength = 0;
for (int i = 0; i < list.size(); i++) {
    if (list.get(i) != null) {
        arrayLength += list.get(i).size();
    }
}

在这里,您必须确定嵌套列表中非null 条目的数量,而不是简单地执行arrayLength += list.get(i).size(),并将此计数添加到arrayLength

for (int k = 0; k < list.get(i).size(); k++) {
    if (list.get(i).get(k) != null) {
       arrayLength++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2020-07-20
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多