Reputation: 23
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?
Upvotes: 2
Views: 48595
Reputation: 1815
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
Upvotes: 4
Reputation: 1322
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.
Upvotes: 4