Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Java error mean?

java.lang.IndexOutOfBoundsException: Index: 1365, Size: 1365
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.Engine.write(Engine.java:114)
at com.Engine.read(Engine.java:90)
at com.Engine.main(Engine.java:19)

I understand that my array is out of bounds, but what does the

Index: 1365, Size: 1365

indicate?

And how could I go by fixing this? Just increase the size of my array?

like image 553
Dennis Martinez Avatar asked Jun 10 '11 18:06

Dennis Martinez


3 Answers

-Size is the size of the array(Amount of elements that can hold).

-Index is the location that you were trying to access.

NOTE 1: Since the first index is 0, you where trying to access 1+ the maximim of the array so that is why you got that exception

FIX OPTION 1

To fix this exception in the case you are using a loop to manipulate the elements you could do something like this:

for(int i = 0; i < array.length; i++) {
   array[i].doSomething();
}

FIX OPTION 2

As you said increasing the size would be another option. You just need to do something like this:

MyArray[] ma =  new MyArray[1366];

BUT That would be not very flexible, in case you want to increase it again in the future. So another option to avoid something like this would be to use a bit more advanced data structure or collection, like a List, because they automatically get increase when in needed. See more information about data structures here: http://tutorials.jenkov.com/java-collections/index.html

Example 1 creation:

List<MyObject> myObjects =  new ArrayList<MyObject>();

Example 2 iteration:

 for(MyObject mo : myObjects) {
     MyObject tmpValue = mo;
    mo.doSomething();  
   }
like image 162
javing Avatar answered Oct 26 '22 18:10

javing


Java arrays are 0-indexed, so if you have an array of size 1365 valid indices are 0, 1, 2, ... 1364. You probably have an off-by-one error in your code: instead of iterating to < length, you iterated to <= length, or similar.

like image 36
Michael Lowman Avatar answered Oct 26 '22 18:10

Michael Lowman


You are accessing index 1365 in an array of 1365 elements. It's out of bounds because the permitted range is 0 to 1364.

Are you accessing your array in a loop? Make sure the counter variable doesn't reach the array's length.

like image 32
BoltClock Avatar answered Oct 26 '22 16:10

BoltClock