2015-11-06 31 views
-1

我必須在Java 1.4中創建類似於結構的表格,並且我認爲要使用字符串數組列表。儘管如此,在插入不同的值後,我的代碼總是從列表的不同位置獲取相同的值。看下面的代碼和生成的輸出。這個Java代碼處理ArrayList有什麼問題?

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

每次要將元素插入idarTable時,都需要創建一個新的String[]。例如:

// 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); 
0

您正在添加相同的數組兩次。您只能更改數組的內容,而不能創建新的數組。