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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With