Friday 21 February 2020

Java: ArrayList: add: IndexOutOfBoundsException

List<String> myList = new ArrayList<String>(10);
myList.add(5, "Hello");

As you see above snippet, I created an ArrayList of initial capacity 10 and trying to add string "Hello" at index 5. But when you run application with above snippet, you will end up in IndexOutOfBoundsException.

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.List;

public class App {

 public static void main(String[] args) {
  List<String> myList = new ArrayList<String>(10);
  myList.add(5, "Hello");
 }

}

Run App.java, you will end up in IndexOutOfBoundsException.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 0
         at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:665)
         at java.util.ArrayList.add(ArrayList.java:477)
         at com.sample.app.App.main(App.java:10)

Explanation
List<String> myList = new ArrayList<String>(10);
Above statement defines ArrayList of capacity 10 and size 0.

myList.add(5, "Hello");
Above snippet tries to insert the string "Hello" at index 5. But while inserting any element to ArrayList, Java checks whether index < size or not. If index is > size or index < 0, then Java throws IndexOutOfBoundsException.

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}



You may like

No comments:

Post a Comment