有很多已解决的多维数组帖子,但我在尝试通过 for 循环创建一个时遇到了困难。
这是我正在尝试做的代码片段。
//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..
谁能告诉我如何使用 for 循环创建这个多维数组。我不想要一个 Person 多维数组。一定要是Object多维数组吗? 谢谢
最佳答案
好吧,你可以这样做:
//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() };
}
这会起作用,但它非常难看。如果我是你,我会考虑让 Swing 更好地“理解”你的 Person
类,以避免完全需要 Object[][]
。
关于java - 使用 for 循环创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400328/