JAVAlang.IndexOutOfBoundsException:索引:0,大小:0在java。util。ArrayList。范围检查
我试图将值设置为类类型的列表。这些值是从数据库(MYSQL)获取的。正在正确获取值,但在设置为“列表”时,可能发生了一些错误
public List<DataFetch> fetchdata(){
List<DataFetch> ob=new ArrayList<DataFetch>();
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = getConnection();
String stm = "Select * from client";
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
int i=0;
while(rs.next()){
String clientname=rs.getString(1);
String clientid=rs.getString(2);
ob.set(i,new DataFetch(clientname,clientid));
i++;
/* ob.setClientname(clientname);
ob.setClientid(clientid);*/
}
// return ob;
} catch (SQLException e) {
e.printStackTrace();
}
return (List<DataFetch>)ob;
}
我试图在console上打印值,但遇到如下问题:
Sep 05, 2015 11:20:24 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/DataTab] threw exception [Index: 0, Size: 0] with root cause
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.set(ArrayList.java:426)
at UserData.fetchdata(UserData.java:49)
at UserData.execData(UserData.java:29)
请给出一个适当的解决方案。提前谢谢
# 1 楼答案
由于试图在空列表中设置元素,因此引发异常。为了消除错误,您必须替换此行(#49):
据此:
没有
i
索引,只需将元素添加到列表中即可