【发布时间】:2018-01-08 02:53:57
【问题描述】:
我在尝试向二维字符串矩阵添加额外的列时遇到重复问题。
这是我的代码:
List<String[]> rowValues; // the matrix, #of rows not
// important, #of columns is 7]
String[] columnValues = new String[8]; // would contain the old row
// data plus one extra String
// LOOP ON ROWS
for(int i = 0; i < rowValues.size(); i++) {
// LOOP ON COLUMNS
for (int j = 0; j < rowValues.get(i).length; j++) {
columnValues[j] = rowValues.get(i)[j];
}
columnValues[7] = "ENTRY" + i;
rowValues.set(i, columnValues);
System.out.println(rowValues.get(i)[0]); // last element in each iteration
}
// END LOOPS
System.out.println(rowValues.get(0)[0]); // element in 0-0 is
// the same as last row-0
我的问题是所有行都包含最后一行的数据,加上标记为的额外列: “输入”
例如,
[hi, im, haithem]
[this, is, hard]
[to, figure, out]
会的,
[to, figure, out, ENTRY2]
[to, figure, out, ENTRY2]
[to, figure, out, ENTRY2]
【问题讨论】:
-
不要将二维数组表示为
List<Foo[]>。使用List<List<Foo>>。 -
或简称为
Foo[][] -
数组列表不是一个好方法。
-
你能添加想要的结果吗?
-
@ChristofferPass 我并不是说尺寸灵活。我的意思是,如果你使用
List,你可以轻松地换掉实现:LinkedList、ArrayList、CopyOnWriteArrayList 等。除非有充分的理由使用它们,否则应避免使用数组。
标签: java for-loop duplicates