我必须在Java 1.4中创建一个类似于结构的表,我想使用一个字符串数组列表。然而,在插入不同的值后,我的代码总是从不同位置的列表中检索相同的值。请参阅下面的代码和生成的输出。
package various_tests;
import java.util.ArrayList;
public class workWithLists {
public static void main(String[] args) {
String[] idarTableRow= new String[3];
String[] line = new String[3];
ArrayList idarTable=new ArrayList();
// Create first row
idarTableRow[0]="A";
idarTableRow[1]="CATAF245";
// add row to table
idarTable.add(idarTableRow);
// Create second row
idarTableRow[0]="B";
idarTableRow[1]="CATAF123";
// add row to table
idarTable.add(idarTableRow);
//Print First row, column one and two
line = (String[]) idarTable.get(0);
System.out.print("Value at row 0: Column 1 is "+ line[0]+" ;Column 2 is "+ line[1]+"\n");
//Print second row, column one and two
line = (String[]) idarTable.get(1);
System.out.print("Value at row 1: Column 1 is "+ line[0]+" ;Column 2 is "+ line[1]+"\n");
}
}
,输出
Value at row 0: Column 1 is B ;Column 2 is CATAF123
Value at row 1: Column 1 is B ;Column 2 is CATAF123
我不明白为什么这只是显示列表中插入的最后一个值而不是列表中位置0和1的不同值。 我做错了什么?
答案 0 :(得分:0)
您要添加两次相同的数组。您只能更改数组的内容,而不是创建新数组。
答案 1 :(得分:0)
每次要将元素插入String[]
时,都需要创建一个新的idarTable
。例如:
// Create first row
idarTableRow = new String[] { "A", "CATAF245" };
// add row to table
idarTable.add(idarTableRow);
// Create second row
idarTableRow = new String[] { "B", "CATAF123" };
// add row to table
idarTable.add(idarTableRow);