I have the following code:
ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0,5);
I am getting an index out of bounds error, and I don't know why. I have declared the ArrayList
of size 10. Why do I get this error?
The index should be in the range 0 to size-1. An IndexOutOfBoundsException is thrown if the index is out of bounds. (For now, this means that the program will halt.) The index must be in the range 0 to size-1, which are the indexes of cells already occupied.
The ArrayIndexOutOfBounds exception is thrown if a program tries to access an array index that is negative, greater than, or equal to the length of the array. The ArrayIndexOutOfBounds exception is a run-time exception. Java's compiler does not check for this error during compilation.
To avoid the ArrayIndexOutOfBoundsException , the following should be kept in mind: The bounds of an array should be checked before accessing its elements. An array in Java starts at index 0 and ends at index length - 1 , so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException .
The most important difference between ArrayList and LinkedList is the distinction between contiguous and non-contiguous memory. ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space.
You declared an ArrayList
, that has the initial capacity of 10 elements, but you did not add an element to this list, i.e. the list is empty. set
will replace an existing element, but since there is no element in the list, the exception is thrown.
You have to add elements before, using the add
method.
Initial capacity
means that the array that the list maintains internally is of size 10 at the beginning. While adding more elements to the list, the size of this internal array might change.
looking into JDK source code of ArrayList.set(int, E)
gives a hint: you need to have at least N
elements in your list before you can call set(N-1, E)
.
Add your elements via add()
method.
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