ArrayList.add抛出ArrayIndexOutOfBoundsException

时间:2012-03-09 10:19:53

标签: java indexoutofboundsexception

我正在尝试将一个对象添加到ArrayList并抛出ArrayIndexOutOfBoundsException 以下是代码

private void populateInboxResultHolder(List inboxErrors){
    inboxList = new ArrayList();
    try{                
        inboxHolder = new InboxResultHolder();
        //Lots of Code
        inboxList.add(inboxHolder);
    }catch(Exception e){
        e.printStackTrace();
    }
}

例外是

[3/7/12 15:41:26:715 UTC] 00000045 SystemErr     R java.lang.ArrayIndexOutOfBoundsException
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr     R      at java.util.ArrayList.add(ArrayList.java:378)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr     R      at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.populateInboxResultHolder(InboxSearchBean.java:388)    
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr     R      at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.searchInboxErrors(InboxSearchBean.java:197)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr     R      at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.viewInbox(InboxSearchBean.java:207)

但是根据ArrayList.add的签名,它不应该抛出这个异常。 请帮忙。

2 个答案:

答案 0 :(得分:25)

ArrayList.add()如果“正确”使用,则永远不应抛出ArrayIndexOutOfBoundsException,因此您似乎以不支持的方式使用ArrayList

很难从您发布的代码中分辨出来,但我的猜测是您从多个线程访问ArrayList

ArrayList未同步,因此不是线程安全的。如果这是问题,您可以使用Collections.synchronizedList()

包裹List来修复此问题

答案 1 :(得分:-2)

您发布的代码不会抛出ArrayIndexOutOfBoundsException。

获取的异常将在您省略的部分中抛出。看看你的堆栈跟踪。它的InboxSearchBean导致异常。很可能它在列表中使用无效索引执行get(索引)。