【问题标题】:How to save multiple arrays into a single arraylist如何将多个数组保存到一个数组列表中
【发布时间】:2019-09-16 20:56:01
【问题描述】:

我正在尝试将循环中生成的数组列表保存到单独的数组列表中。它不允许我这样做;我收到一个错误:

public static void ranCentroid() {
        Random randomPoint = new Random();
        Cent = new ArrayList<>();
        for (int i = 0; i < numCen; i++) {
            int randomP = randomPoint.nextInt(Points.size());
            System.out.println(Points.get(randomP));
            Cent.get(i).add(randomP);
        }
        System.out.println(Cent);

    }

遇到错误

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at phase1.Main.ranCentroid(Main.java:100)
    at phase1.Main.main(Main.java:41)

【问题讨论】:

  • 数组与ArrayList 不同。你和哪个合作?这对您需要做的事情有很大的影响。
  • 一个 ArrayList ...
  • Cent 仍然是空的,所以 get 将不起作用...需要先向其中添加一些 (numCen) 新列表 - 也可以将 array 用于数组 (...[]) 而不是列表,让很多人感到困惑

标签: java arrays


【解决方案1】:

我假设 Points 是一个列表,因为您调用了方法 Points.size()Points.get(x)。总结您的结果声明一个新列表并使用方法List.addAll

public static void ranCentroid() {
    Random randomPoint = new Random();
    List<Double> result = new ArrayList<>();
    for (int i = 0; i < numCen; i++) {
        int randomP = randomPoint.nextInt(Points.size());
        result.addAll(Points.get(randomP));            
    }
    System.out.println(result);
}

编辑

如果您需要一个列表作为结果:

public static void ranCentroid() {
    Random randomPoint = new Random();
    List<List<Double>> result = new ArrayList<>();
    for (int i = 0; i < numCen; i++) {
        int randomP = randomPoint.nextInt(Points.size());
        result.add(Points.get(randomP));            
    }
    System.out.println(result);
}

【讨论】:

  • 这将每个元素变成一个元素,并且不保留它们的数组结构。
  • @Ant 我不明白你的意思。如果您显示列表的示例输入 Points 和预期的输出,可能会更容易。
  • @Ant 如果您需要列表作为结果,请查看我的编辑。
【解决方案2】:

您要做的是减少功能。归约函数接受一个集合并将其减少一步。所以在这种情况下,一个二维数组变成了一个一维数组。

您也可以不使用内置归约函数,方法是创建一个数组列表,然后循环遍历您的元素并将其添加到您创建的数组列表中。

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多