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);
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 .
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 .
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.
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.
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
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.
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