java - ArrayList.add 抛出 ArrayIndexOutOfBoundsException

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

异常(exception)的是

[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 的签名,它不应该抛出这个异常。 请帮忙。

最佳答案

ArrayList.add() 如果“正确”使用,则永远不应抛出 ArrayIndexOutOfBoundsException,因此看起来您正在使用 ArrayList它不支持的方式。

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

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

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

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

关于java - ArrayList.add 抛出 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9632387/

相关文章:

java - 及格类<?扩展 T> 作为参数

java - File.list() 的运行时间?

java - 验证值并引发异常

ios - 后台线程更新变量并导致索引越界 swift ios

java - java数组索引越界

java - 在 JDBC 中插入单引号以进行 SQL 查询不起作用

java - 无法在Java中调用验证方法

java - 将自定义值传递给 Reducer

java - 解决简单的 ArrayIndexOutOfBoundsException

java - 子串奇怪的界限?