Amir Ghahrai
Amir Ghahrai

Reputation: 619

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

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?

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

Upvotes: 0

Views: 1465

Answers (3)

robonerd
robonerd

Reputation: 198

Does your 2d array contain exactly 3 columns? 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;
}

Upvotes: 0

Hakan Serce
Hakan Serce

Reputation: 11256

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()));

Upvotes: 2

Cat
Cat

Reputation: 67502

In your for loop, instead of looping through j, call your constructor.

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:

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. As this was vizier's solution, please upvote/accept his answer.

Upvotes: 0

Related Questions