0

我有一堂课

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;
    }

}

另一个从文件中获取数据并返回二维对象数组的类

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;
}
4

3 回答 3

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()));
于 2012-06-06T21:03:32.113 回答
0

您的二维数组是否正好包含 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;
}
于 2012-06-06T21:07:32.643 回答
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.

编辑:更新以添加toString到每个 SimpleData 构造函数。由于这是vizier的解决方案,请投票/接受他的回答。

于 2012-06-06T21:03:30.510 回答