我有一个班级
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;
}
答案 0 :(得分:2)
而不是
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()));
答案 1 :(得分:0)
在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 /接受他的回答。
答案 2 :(得分:0)
你的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;
}