I am trying to add a object to a ArrayList and its throwing ArrayIndexOutOfBoundsException Following is the code
private void populateInboxResultHolder(List inboxErrors){ inboxList = new ArrayList(); try{ inboxHolder = new InboxResultHolder(); //Lots of Code inboxList.add(inboxHolder); }catch(Exception e){ e.printStackTrace(); } }
And the exception is
[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)
But according to the signature of ArrayList.add it should not throw this exception. Please help.
The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.
Use Proper Start And End Indices Arrays always start with index 0 and not 1. Similarly, the last element in the array can be accessed using the index 'arraylength-1' and not 'arraylength'. Programmers should be careful while using the array limits and thus avoid ArrayIndexOutOfBoundsException.
ArrayIndexOutOfBoundsException occurs when we access an array, or a Collection, that is backed by an array with an invalid index. This means that the index is either less than zero or greater than or equal to the size of the array. Additionally, bound checking happens at runtime.
ArrayList.add()
should never throw an ArrayIndexOutOfBoundsException
if used "properly" so it seems that you're using your ArrayList
in a way which it does not support.
It's hard to tell from just the code you've posted but my guess is that you're accessing your ArrayList
from multiple threads.
ArrayList
isn't synchronised and so isn't thread safe. If this is the problem you can fix it by wrapping your List
using Collections.synchronizedList()
.
Changing your code to the following should resolve the problem:
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With