Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a multi-dimensional array using a for loop

There are many solved multi-dimensional array posts, but I am having difficulties trying to create one through a for loop.

This is the code snippet of code that I am trying to do.

//Get a list of Person objects using a method
ArrayList<Person> people = getPeopleList();

//Create an array of 10 Objects with 4 values each
Object[][] data = new Object[10][4];

int count =1;
for(Person p: people)
{
    //This wont compile. This line is trying to add each Object data with values
    data[count-1][count-1] = {count, p.getName(), p.getAge(), p.getNationality()};
    count++;
}

//I then can add this data to my JTable..

Can anyone tell me how I can create this multi-dimensional array using the for loop. I don't want a Person multi-dimensional array. It needs to be an Object multi-dimensional array? Thanks

like image 371
Douglas Grealis Avatar asked Dec 11 '22 15:12

Douglas Grealis


1 Answers

Well, you can do this:

//Get a list of Person objects using a method
ArrayList<Person> people = getPeopleList();
Object[][] data = new Object[people.size()][];

for(int i = 0; i < people.size(); i++)
{
    Person p = people.get(i);
    data[i] = new Object[] { i, p.getName(), p.getAge(), p.getNationality() };
}

That will work, but it's very ugly. If I were you, I'd look into making Swing "understand" your Person class better, to avoid requiring the Object[][] at all.

like image 196
Jon Skeet Avatar answered Dec 19 '22 19:12

Jon Skeet