简体   繁体   中英

Exception : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

I'm trying to instantiate a Java bean, however it throws

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

Here's the relevant code of BooksManager class:

private BooksTable booksTable;
private BookGenerator bookGenerator;

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

And the BooksTable class:

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

How is this caused and how can I solve it?

Try changing:

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

to:

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

Hope that helps.

Reason :

     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
  }                                                                                                

add the one more validation in the if : this.bookList.size() == 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM