2016-05-31 101 views
-4

我想從mysql數據庫中獲取位置名稱。我想檢索所有位置名稱並收集到ArrayList和此列表請求setAttribute到jsp。將String []轉換爲ArrayList

ArrayList<Bean> SupplyLocation = new ArrayList<Bean>(); 
try { 
//... 
    while(rs.next()) { 
     Bean Location = new Bean(); 
     String supply[] = (rs.getString("location_name")).split(","); 

     for(int i=0; i<supply.length; i++) { 
      Location.setLocation(supply); 
      SupplyLocation.add(Location); 
     }     
    } 
} 

回答

1

您創建了一個對象Location,所以在後面的循環進行修改,所以你最終會與supply從該對象supply[lastIndex]一個對象,並在ArrayList所有引用將指向它。

修正:

while(rs.next()) { 
     String supply[] = (rs.getString("location_name")).split(","); 

     for(int i=0; i<supply.length; i++) { 
      Bean Location = new Bean(); 
      Location.setLocation(supply[i]); 
      SupplyLocation.add(Location); 
     } 
} 

這樣,你在supply數組創建新的對象Bean每個字符串,然後設置字符串supply[i]它,你把對它的引用在SupplyLocation

0

考慮到您的字符串是逗號分隔,然後做到這一點,

String supply[] = (rs.getString("location_name")).split(","); 

     for(int i=0; i<supply.length; i++) { 
      Location.setLocation(supply); 
      SupplyLocation.add(Location.toString()); 
     }   
+0

這不會編譯... –

相關問題