Douglas Grealis
Douglas Grealis

Reputation: 619

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

Upvotes: 4

Views: 352

Answers (3)

Eric Jablow
Eric Jablow

Reputation: 7899

data is an Object[][]. So, data[count - 1] is an Object[]. And then data[count - 1][count - 1] is an Object. Look at Jon Skeet's answer, and then look at the TableModel interface, documented at http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableModel.html. Then, look at the Java Tutorial linked from there.

You do not need to take the people variable and turn it into another type of object the way you are doing now.

Upvotes: 2

isaach1000
isaach1000

Reputation: 1839

You need to have a nested for loop that goes through each element of the Person. The current code will not compile because you are setting one location of the array to an invalid value. Alternatively, you can create a method in Person that returns an array and set the values of a single dimensional array with the Person array.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 9

Related Questions