将String []转换为ArrayList

时间:2016-05-31 13:11:42

标签: java arraylist

我想从mysql数据库中获取位置名称。我想检索所有位置名称并收集ArrayListsetAttribute请求的此列表到jsp。

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);
        }                
    }
}

2 个答案:

答案 0 :(得分:1)

您只创建了一个对象supply,因此稍后会在for循环中对其进行修改,因此您最终将在该对象中使用supply[lastIndex]的{​​{1}}对象,并且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);
        }  
}

通过这种方式,您可以为Bean数组中的每个字符串创建新对象supply,然后将字符串supply[i]设置为它,并在{{1}中对其进行引用}}

答案 1 :(得分:0)

考虑到你的字符串以逗号分隔,然后执行此操作,

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

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