Creating a multidimensional array using a for loop

There are many permitted multidimensional array messages, but I'm having difficulty trying to create a single for loop.

This is the code snippet of the code I'm 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 someone tell me how I can create this multidimensional array using a for loop. I do not want a multidimensional array of Person. Should it be a multi-dimensional array of Object? Thanks

+4
source share
3 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() }; } 

It will work, but it is very ugly. If I were you, I would look to make Swing โ€œunderstandโ€ your Person class better, without requiring Object[][] .

+9
source

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

+2
source

data is Object[][] . So data[count - 1] is Object[] . And then data[count - 1][count - 1] is Object . Look at John 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 that is there.

You do not need to take the people variable and turn it into an object of a different type as you are doing now.

+2
source

Source: https://habr.com/ru/post/1479362/


All Articles