skip to Main Content

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.

5

Answers


  1. 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!

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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-

    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
  5. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search