gpt4 book ai didi

java - 如何在 Java 中的二维数组上的循环内创建对象

转载 作者:行者123 更新时间:2023-12-02 07:45:32 24 4
gpt4 key购买 nike

我有课

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 对象数组

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

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

在循环遍历二维数组并将对象添加到列表中时,如何创建 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()));

关于java - 如何在 Java 中的二维数组上的循环内创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com