Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList index out of bounds

Tags:

java

arraylist

Why java.lang.IndexOutOfBoundsException is raised in this example, if the size of ArrayList has been predefined? How to solve this problem?

int size = 2:
ArrayList<Integer[]> nums = new ArrayList<Integer[]>(size);
Integer[] value1 = {1,2,3};
Integer[] value2 = {1,2};
nums.add(1,value1); // java.lang.IndexOutOfBoundsException
nums.add(0,value2);
like image 246
Klausos Klausos Avatar asked Jan 04 '12 15:01

Klausos Klausos


People also ask

How do you fix array index 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 .

What is array index out of bounds?

When accessing an array element, one must ensure that the index is less than the length of the array. Using an index that is greater than or equal to the array length causes an ArrayIndexOutOfBoundsException .

What does index 0 out of bounds for length 0 mean?

ArrayIndexOutOfBoundsException length=0 index=0. This is the classic case of accessing an empty array. Since length is zero it means the array is empty and the index is zero means we are trying to access the first element of the array.

What is Java index out of bounds?

The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.


2 Answers

You cannot put an item in an ArrayList before the other one is set. If you want to do it you'll have to assign null values to the item on place 0 first.

It will work if you do:

int size = 2:
ArrayList<Integer[]> nums = new ArrayList<Integer[]>(size);
Integer[] value1 = {1,2,3};
Integer[] value2 = {1,2};
nums.add(0, null);
nums.add(1,value1);
nums.set(0,value2);

edit/ Replaced add by set to replace the null object

like image 173
J. Maes Avatar answered Oct 18 '22 17:10

J. Maes


The argument to the ArrayList constructor isn't the size of the list, as your code is assuming; it's the capacity of the underlying storage used by the data structure.

The capacity will grow as required as you add elements to the list. The only reason to specify the initial capacity in the constructor is to pre-allocate a larger capacity if you know you're going to be adding lots of elements. This means that the underlying array doesn't havwe to be resized too often as you add them.

Regardless of what value you specify in the ArrayList constructor, the size of the list is governed solely by what you put into it, so you can't fetch the item with index of 1 until you've added at least 2 elements.

like image 28
skaffman Avatar answered Oct 18 '22 17:10

skaffman