如何将多个数组保存到单个数组列表中

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


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)


慕村225694
浏览 115回答 2
2回答

浮云间

我假设 Points 是一个列表,因为您调用方法Points.size()和Points.get(x)。要总结您的结果,请声明一个新列表并使用以下方法List.addAll:public static void ranCentroid() {&nbsp; &nbsp; Random randomPoint = new Random();&nbsp; &nbsp; List<Double> result = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < numCen; i++) {&nbsp; &nbsp; &nbsp; &nbsp; int randomP = randomPoint.nextInt(Points.size());&nbsp; &nbsp; &nbsp; &nbsp; result.addAll(Points.get(randomP));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(result);}编辑如果您需要一个列表列表作为结果:public static void ranCentroid() {&nbsp; &nbsp; Random randomPoint = new Random();&nbsp; &nbsp; List<List<Double>> result = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < numCen; i++) {&nbsp; &nbsp; &nbsp; &nbsp; int randomP = randomPoint.nextInt(Points.size());&nbsp; &nbsp; &nbsp; &nbsp; result.add(Points.get(randomP));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(result);}

www说

您要做的是减少功能。缩减函数接受一个集合并将其向下一级缩减。因此,在本例中,将 2D 数组转换为 1D 数组。您也可以在不使用内置归约函数的情况下通过创建数组列表、循环遍历元素并将其添加到您创建的数组列表中来完成此操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java