例外:java.lang.IndexOutOfBoundsException:索引:0,大小:0

时间:2013-07-29 14:46:42

标签: java indexoutofboundsexception

我正在尝试实例化一个Java bean,但它会抛出

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at com.application.jsf.BooksTable.getLastId(BooksTable.java:54)
    at com.application.jsf.BooksManager.<init>(BooksManager.java:24)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:374)
    at java.lang.Class.newInstance(Class.java:327)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    ... 55 more

以下是BooksManager类的相关代码:

private BooksTable booksTable;
private BookGenerator bookGenerator;

public BooksManager() {
    booksTable = new BooksTable();
    bookGenerator = new BookGenerator(booksTable.getLastId());
}

BooksTable类:

private ArrayList<BookBean> booksList;
private int BOOKS_ON_PAGE = 10;

BooksTable(){
    this.booksList = new ArrayList<BookBean>();
}

public int getLastId(){
    if(this.booksList == null){
        return -1;
    }
    return this.booksList.get(this.booksList.size()).getBookId();
}

这是如何引起的?如何解决?

2 个答案:

答案 0 :(得分:4)

尝试更改:

public int getLastId(){
if(this.booksList == null){
    return -1;
}
return this.booksList.get(this.booksList.size()).getBookId();
}

为:

public int getLastId(){
if(this.booksList == null || this.booksList.size() == 0){
    return -1;
}
return this.booksList.get(this.booksList.size()-1).getBookId();
}

希望有所帮助。

答案 1 :(得分:4)

原因:

     public int getLastId(){
         if(this.booksList == null){
           return -1;
         }
         return this.booksList.get(this.booksList.size()).getBookId(); //This line causing the problem when calling from BookManager
  }                                                                                                

在if:this.bookList.size()== 0

中添加一个验证