Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList out of bounds exception

Tags:

java

arraylist

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?

like image 609
TimeToCodeTheRoad Avatar asked Jan 17 '12 13:01

TimeToCodeTheRoad


People also ask

Can ArrayList go out of bounds?

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.

Why is my ArrayList out of bounds?

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.

How do you handle an array out of bounds exception?

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 .

Do ArrayLists have to be contiguous?

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.


2 Answers

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.

like image 152
hage Avatar answered Oct 04 '22 22:10

hage


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.

like image 31
Victor Sorokin Avatar answered Oct 04 '22 21:10

Victor Sorokin