简体   繁体   English

如何在Java中的2d数组中创建循环内的对象

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

I have a class 我上课了

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

}

And another class that gets data from a file and returns a 2d Object array 另一个从文件中获取数据并返回2d Object数组的类

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

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

How can I create objects of SimpleData when looping through the 2d array and adding the objects to a list so that each object of SimpleData represents a row of data? 如何在循环遍历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;
}

Instead of 代替

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

You will need this (ignoring exception handling): 你需要这个(忽略异常处理):

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

In your for loop, instead of looping through j , call your constructor. 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.
}

You can also make an ArrayList of SimpleDatas, for example: 您还可以创建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.

EDIT: Updated to add toString to each SimpleData constructor. 编辑:更新为每个SimpleData构造函数添加toString As this was vizier 's solution, please upvote/accept his answer. 由于这是vizier的解决方案,请upvote /接受他的回答。

Does your 2d array contain exactly 3 columns? 你的2d数组是否包含3列? If so here is the code. 如果是这样,这里是代码。

 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