簡體   English   中英

如何在Java中的2d數組中創建循環內的對象

[英]How to create objects inside a loop on 2d array in Java

我上課了

public class SimpleData() {
    String continent;
    String country;
    String city;

    public SimpleData(String continent, String country, String city) {
        this.continent = continent;
        this.country = country;
        this.city = city;
    }

}

另一個從文件中獲取數據並返回2d Object數組的類

private Object[][] getDataFromFile(String fileName) {
    return dataLoader.getTableArray(fileLocation, dataSheetName);
}

//will return something like
europe, uk, london
europe, france, paris

如何在循環遍歷2d數組並將對象添加到列表中時創建SimpleData對象,以便SimpleData的每個對象代表一行數據?

private List<SimpleData> getDataList() {
    Object[][] array = readDataFromFile("myfile");
    List<SimpleData> dataList = new ArrayList<SimpleData>();

    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            //what's the code to generate object with the correct row of data?
        }
    }
    return dataList;
}

代替

    for (int j = 0; j < arr[i].length; j++) {
        //what's the code to generate object with the correct row of data?
    }

你需要這個(忽略異常處理):

dataList.add(new SimpleData(array[i][0].toString(), array[i][1].toString(), 
   array[i][2].toString()));

for循環中,不是循環遍歷j ,而是調用構造函數。

for (int i = 0; i < arr.length; i++) {
    SimpleData yourData = new SimpleData(arr[i][0].toString(), arr[i][1].toString(), arr[i][2].toString());
    // Whatever you want with yourData.
}

您還可以創建SimpleDatas的ArrayList,例如:

ArrayList<SimpleData> datas = new ArrayList<SimpleData>();
for (int i = 0; i < arr.length; i++) {
    datas.add(new SimpleData(arr[i][0].toString(), arr[i][1].toString(), arr[i][2].toString()));
}
// Whatever you want with datas.

編輯:更新為每個SimpleData構造函數添加toString 由於這是vizier的解決方案,請upvote /接受他的回答。

你的2d數組是否包含3列? 如果是這樣,這里是代碼。

 private List<SimpleData> getDataList() {
    Object[][] array = readDataFromFile("myfile");
    List<SimpleData> dataList = new ArrayList<SimpleData>();

    for (int i = 0; i < arr.length; i++) {
        SimpleData sd = new SimpleData(array[i][0], array[i][1], array[i][2]);
        dataList.add(sd);
        }
    }
    return dataList;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM