22

我正在尝试将对象添加到 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 的签名,它不应该抛出这个异常。请帮忙。

4

2 回答 2

40

ArrayList.add()永远不应该抛出ArrayIndexOutOfBoundsExceptionif used "properly" 所以看起来你正在以ArrayList它不支持的方式使用你的。

仅从您发布的代码很难分辨,但我的猜测是您正在ArrayList从多个线程访问您的代码。

ArrayList不同步,因此不是线程安全的。如果这是问题,您可以通过包装Listusing来解决它Collections.synchronizedList()

将代码更改为以下内容应该可以解决问题:

private void populateInboxResultHolder(List inboxErrors){
    List inboxList = Collections.synchronizedList(new ArrayList());
    try{                
        inboxHolder = new InboxResultHolder();
        //Lots of Code
        inboxList.add(inboxHolder);
    }catch(Exception e){
        e.printStackTrace();
    }
}
于 2012-03-09T10:25:24.690 回答
-3

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

得到的异常会在您省略的部分中引发。看看你的堆栈跟踪。导致异常的 InboxSearchBean。很可能它在具有无效索引的列表上执行 get(index)。

于 2012-03-09T11:46:58.703 回答