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

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

如何從 2 個現有的 ArrayLists (Java) 創建一個矩陣?

如何從 2 個現有的 ArrayLists (Java) 創建一個矩陣?

翻閱古今 2021-12-30 20:48:05
我正在從文本文件中讀取內容并將它們解析為單獨的 ArrayLists。例如,文本文件內容如下:Fruit1Fruit2Fruit3Vegetable1Vegetable2Vegetable3Vegetable4目前,我有一個代碼將每個組分成自己的數組fruits = [Fruit1, Fruit2, Fruit3]vegetables = [Vegetable1, Vegetable2, Vegetable3, Vegetable4]如何從這兩個現有的 ArrayLists制作一個包含n行和m列的矩陣?我的目標輸出是像這樣生成一個 3x4 矩陣          | Fruit1, Fruit2, Fruit3 Vegetable1|Vegetable2|Vegetable3|Vegetable4|           |我已經看到了演示初始化矩陣的示例,但是,如果我更新我的文本文件以假設 3x20 矩陣或 5x20 矩陣,我希望代碼運行相同,這就是我掙扎的地方。這是我為矩陣編寫的代碼:List<List<String>> matrix = new ArrayList<List<String>>();matrix.add(fruits);matrix.add(vegetables);System.out.println(matrix);然而,這是輸出,它只是將它們組合起來[Fruit1, Fruit2, Fruit3, Vegetable1, Vegetable2, Vegetable3, Vegetable4]如何創建一個矩陣,使一個 ArrayList 為行,另一個 ArrayList 為列?
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

假設您需要以下矩陣:


Vegetable1 | Fruit1, Fruit2, Fruit3

Vegetable2 | Fruit1, Fruit2, Fruit3

Vegetable3 | Fruit1, Fruit2, Fruit3

Vegetable4 | Fruit1, Fruit2, Fruit3

您可以使用以下代碼使用ArrayLists 進行所有比較:


List<String> vegetables = new ArrayList<>(); // Fill the lists somehow

List<String> fruits = new ArrayList<>();


for(String vegetable : vegetables) {

    for(String fruit : fruits) {

        System.out.printf("Compare %s to %s%n", vegetable, fruit);

    }

}

如果這就是您想要的,您就不需要嵌套列表。如果您真的想擁有一個矩陣,那么您需要對代碼稍作修改:


List<String> vegetables = new ArrayList<>(); // Fill the lists somehow

List<String> fruits = new ArrayList<>();

List<List<String>> matrix = new ArrayList<>();    


for(String vegetable : vegetables) {

    List<String> row = new ArrayList<String>();

    row.add(vegetable);

    for(String fruit : fruits) {

        row.add(fruit);

    }

    matrix.add(row);

}

這將創建包含項目的行,VegetableN, Fruit1, Fruit2, Fruit3其中 N 是蔬菜行的編號。


查看完整回答
反對 回復 2021-12-30
  • 1 回答
  • 0 關注
  • 250 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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