简体   繁体   中英

Getting IndexOutOfBoundsException in ArrayList while using .add(index, element)

I am using the list.add(index, element) function to insert elements into an ArrayList, where the index is not in order.

For eg, first i call list.add(5, element5) and then list.add(3, element3)

I am getting the exception java.lang.IndexOutOfBoundsException: Invalid index 5, size is 0 exception.

Please tell where I am doing wrong and how can I fix this.

You cannot add elements to indexes which do not yet exist. In general, as Japhei said, you can only add elements to indexes smaller or equal to the array length. This means, if your ArrayList is still empty, you can only add elements at index 0 or without specifying the index (which will just add it to the end).

What you want to do is initialize your ArrayList with empty elements. I normally use meaningless values like 0 or -1 for integers or empty strings depending on the array type (or null elements), and just fill them later.

But if you know how many elements you have, or what array size you need, why not just use a normal array? That would be the right way to do it.

The problem is that your ArrayList is empty and therefore the insert (via add(int index, E element) fails.

Consider using the add(E element) ( documentation ) to add the element to the end of the list.

So what is probably happening is, that you defined a size for your list on creating said list. According to your error message this would be 0. And on a list with the size 0, you can't set the 5th or 3rd position to anything, as they don't exist. If you would add the line where you define the variable "list", we could help you further!

You can't add to index not in list range:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

See java doc: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E-

You can only use indexes that are existing or one larger than the last existing. Otherwise you would have some spots with no element in it. If you need a ficxed length to store elements on a specified position, try to fill the List before with empty entries or use an array:

MyElement[] myArray = new MyElement[theLengthOfMyArray];
myArray[5] = elementXY;

Or fill a List with null elements ( shown here ):

List<MyElement> myList = new ArrayList<>();
for (int i = 0; i < theTargetLengthOfMyList; i++) {
    myList.add(null);
}
myList.set(5, elementXY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM