java - 异常 : java. lang.IndexOutOfBoundsException : Index: 0, 大小:0

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

这是怎么造成的,如何解决?

最佳答案

尝试改变:

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

希望有帮助。

关于java - 异常 : java. lang.IndexOutOfBoundsException : Index: 0, 大小:0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17927069/

相关文章:

java - 字符串索引越界异常 : String index out of range: 4

java - 将通用类型 <T> 的元素添加到 LinkedList 的 arrayList

java - FileServlet(BalusC 的解决方案)在 IE 中不显示保存对话框

java - 转换为二进制 - 获取 IndexOutOfBoundsException

Java 8 模式匹配?

java - Java 和 Python 的执行速度

android - 使用 ArrayIndexOutOfBoundsException 将 TextView 文本设置为静态文本崩溃(很少)

java - 打乱 LinkedList 时出现 ArrayIndexOutOfBoundsException

java - 无法使用 Apache CXF Soap 通过代理建立隧道

java - 无法编辑看似任意的 JTable 列