0

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

3 Answers 3

2

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()));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

SimpleData constructors take String arguments, so you should convert Objects to Strings.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.