亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將多個數組保存到單個數組列表中

如何將多個數組保存到單個數組列表中

慕村225694 2023-08-04 14:48:36
我試圖將循環中生成的數組列表保存到單獨的數組列表中。它不允許我這樣做;我收到錯誤: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)
查看完整描述

2 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

我假設 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);

}


查看完整回答
反對 回復 2023-08-04
?
www說

TA貢獻1775條經驗 獲得超8個贊

您要做的是減少功能??s減函數接受一個集合并將其向下一級縮減。因此,在本例中,將 2D 數組轉換為 1D 數組。

您也可以在不使用內置歸約函數的情況下通過創建數組列表、循環遍歷元素并將其添加到您創建的數組列表中來完成此操作。


查看完整回答
反對 回復 2023-08-04
  • 2 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號