Java add抛出ArrayIndexOutOfBoundsException

Java add抛出ArrayIndexOutOfBoundsException,java,indexoutofboundsexception,Java,Indexoutofboundsexception,我试图向ArrayList添加一个对象,并将其抛出ArrayIndexOutOfBoundsException 下面是代码 private void populateInboxResultHolder(List inboxErrors){ inboxList = new ArrayList(); try{ inboxHolder = new InboxResultHolder(); //Lots of Code

我试图向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的签名,它不应该抛出这个异常。
请提供帮助。

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

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

ArrayList
不同步,因此线程不安全。如果这是一个问题,您可以通过使用包装您的
列表来解决它

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

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();
    }
}
您发布的代码不会抛出ArrayIndexOutOfBoundsException


您得到的异常将在您忽略的部分中抛出。看看你的跟踪记录。导致异常的InboxSearchBean。它很可能对索引无效的列表执行get(索引)。

由于IndexOutOfBoundsException是一个运行时异常,因此可以在方法签名中不提及的情况下抛出它。
ArrayIndexOutOfBoundsException
是一个运行时异常,而不是检查异常,所以它不一定会出现在抛出它的方法的签名中。没错。但是如果你看add方法本身,这个异常不可能被抛出。我确实从这个角度考虑过。但是即使在这种情况下,它也不应该抛出这个异常,因为我们正在进行add而不是add(index,Obj)。如果从多个线程访问
ArrayList
,而不同步,则它将中断。我认为发生的情况是,两个线程试图同时修改
ArrayList
下的
数组,因此当其中一个线程尝试添加新值时,它的大小不正确。否。如果你使用合同之外的东西,它的行为就会变得不明确。这意味着您可以期望它抛出任何
RuntimeException
,或损坏您的数据或执行任何操作。文档清楚地表明,
ArrayList
在多线程中不受支持,因此在这种情况下不会有任何已定义的行为。它引发了此异常,因为它试图向索引过大的
数组添加内容。
ArrayList
将其数据存储在
Array
中,并自动保持该
数组的大小。但是,如果同时从多个线程访问
ArrayList
,则维护代码的
ArrayIndexOutOfBoundsException
并不总是以“正确的顺序”运行,因此您会得到
ArrayIndexOutOfBoundsException。幸运的是你得到了一个例外,而不仅仅是一些腐败或丢失的数据。如果您从多个线程访问
ArrayList
,这肯定是问题的根源。不,谢谢。除非您尝试使用
Collections.synchronizedList()
,否则没有什么可讨论的,而且这并没有解决问题。