【发布时间】:2013-02-28 09:38:34
【问题描述】:
我有一个包含对象的数组列表。每个对象包含许多字符串。我正在尝试将这些字符串添加到二维数组中。
public void iterateRow(Row row)
{
int x = 0;
int y = size();
tableArray = new String[y][5];
while(x < y){
int z = 0;
for (String s: row.rowString()){
tableArray[x][z] = s;
z++;
}
x++;
}
}
每当我运行并为行类创建一个新实例时,该方法都应将包含在 Row 中的字符串添加到数组中。但是,它将最新条目复制 x 次(其中 x 是条目总数)。
这里是 Row 类供进一步参考:
public class Row
{
public String appNumber;
public String name;
public String date;
public String fileLoc;
public String country;
public String elementString;
public String results[];
public Row(String appNumber, String name, String date, String fileLoc, String country, Table table)
{
this.appNumber = appNumber;
this.name = name;
this.date = date;
this.fileLoc = fileLoc;
this.country = country;
table.addApplicant(this);
}
public String[] rowString()
{
String[] a = {appNumber, name, date, fileLoc, country};
return a;
}}
我认为在 iterateRow() 方法中这是一个愚蠢的逻辑错误,但我似乎无法弄清楚是什么。任何帮助将不胜感激。
编辑:在大家的帮助下,我删除了 while 循环。然而,它似乎仍然是复制行而不是移动到下一个?
public void iterateRow(Row row)
{ int x = 0;
int y = size();
tableArray = new String[y][row.rowString().length];
for(int i =0; i<y;i++){
int z = 0;
for (String s: row.rowString()){
tableArray[x][z] = s;
z++;
}x++;}
}
【问题讨论】:
-
size()返回什么?因为您将同一行rowString()元素添加到您的数组"size()"次。 -
根据您的循环,由于参数“行”永远不会改变,您构建数组的源将来自此“行”。我想在你的'for each'循环之后你想去下一行吗?......而且,你的while循环可以简化为'for'循环。
-
这里为什么是 5,tableArray = new String[y][5] ?
-
因为Row中有5个String字段。
-
@Machinegon 好声音。我已将其更改为 tableArray = new String[y][row.rowString().length];
标签: java arrays object arraylist add