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

Time:07-05

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.

CodePudding user response:

Correct me if I'm wrong, but I think you cannot add elements to indexes which do not yet exist if that helps. If the ArrayList is still empty, you can only add elements without specifying the index.

CodePudding user response:

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.

CodePudding user response:

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!

CodePudding user response:

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-

CodePudding user response:

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);
  • Related