2016-03-08 83 views
0

下面是一段代碼段,用於提取arraylist的一部分。我的數組列表full包含大約3000行,每行193個數字用空格分隔。 現在我想分割我的數組列表,以獲得每行中的前48位數字,即我的最後一個「ocr」數組列表應包含3000行,每行有48位數字以空格分隔。拆分arraylist java

在這裏,當我嘗試將臨時複製到ocr,然後打印ocr,我得到整個arraylist,而不是一個子列表。這段代碼有什麼問題?

void extractData(){ 

    ArrayList<points> test1 = new ArrayList<points>(); 
    points temp = new points(); 

    for (points p : full){ 
     for (int i = 0; i < 48; i++){ 
      temp.x[i] = p.x[i]; 
     } 
     ocr.add(temp); 

    } 
    for (points pp : ocr) 
     System.out.println(pp);  
} 
+1

由於您在循環外部創建了相同的單個'temp'對象,因此多次添加'ocr'對象。這可能是你的問題的一部分,儘管由於你沒有顯示足夠的上下文,所以我不能分辨是否是你的整個問題。 – Boann

+2

另外,請尊重Java命名約定以使您的代碼可讀。類以大寫字母開頭。 –

回答

0

您的臨時「臨時」變量在每次迭代中都被重複使用。在外部循環中移動聲明來修復它。

void extractData() 
{ 

    List<points> test1 = new ArrayList<>(); 

    for (points p : full) 
    { 
     points temp = new points(); 
     for (int i = 0; i < 48; i++) 
     { 
      temp.x[i] = p.x[i]; 
     } 
     ocr.add(temp); 

    } 
    for (points pp : ocr) 
    { 
     System.out.println(pp); 
    } 
} 

另請注意註釋中提到的Java命名約定。