2016-05-31 76 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

这不会编译... –

相关问题