java.lang.IndexOutOfBoundsException:Index:0,size:0 at java.util.ArrayList.rangeCheck

时间:2015-09-05 18:33:34

标签: java

我正在尝试将值设置为类类型的列表。这些值是从数据库(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;

    }

我正在尝试在控制台上打印这些值,但问题如下:

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 个答案:

答案 0 :(得分:1)

抛出异常是因为您尝试在空List中设置元素。为了摆脱错误,你必须更换这一行(#49):

$first_zone_array = $jfo->apr[0]; //This gets the following:
object(stdClass)#2 (2) { ["f1"]=> string(6) "139eg1" ["zones"]=> array(5) { [0]=> object(stdClass)#3 (2) { ["f2"]=> string(7) "unknown" ["zone"]=> string(3) "123" } [1]=> object(stdClass)#4 (2) { ["f2"]=> string(7) "unknown" ["zone"]=> string(3) "321" } [2]=> object(stdClass)#5 (2) { ["f2"]=> string(7) "unknown" ["zone"]=> string(3) "123" } [3]=> object(stdClass)#6 (2) { ["f2"]=> string(3) "top" ["zone"]=> string(3) "321" } [4]=> object(stdClass)#7 (2) { ["f2"]=> string(7) "unknown" ["zone"]=> string(3) "123" } } }

由此:

           `ob.set(i,new DataFetch(clientname,clientid));`

没有 `ob.add(new DataFetch(clientname,clientid));` 索引,只需向List添加元素。