簡體   English   中英

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

[英]Exception : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

我正在嘗試實例化一個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();
}

希望有所幫助。

原因:

     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中再添加一個驗證

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM