Physicsman
Physicsman

Reputation: 181

ArrayList - Index vs Size

I received the following error when trying to print an ArrayList of 698 items:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 698, Size: 698

I used the following code which I expected to get an error for:

 Mylist.top(1000);

My question is, if the size of the array is 698, then shouldn't the max index be 697? I don't understand why the error gives Index: 698.

Upvotes: 0

Views: 1789

Answers (2)

Juanje
Juanje

Reputation: 1315

The error is raising when you are trying to access index 698. You are right, max index is 697, so error will raise in the following index.

Upvotes: 0

Ben P.
Ben P.

Reputation: 54264

if the size of the array is 698, then shouldn't the max index be 697? I don't understand why the error gives Index: 698.

That's exactly why it's an error.

The error is IndexOutOfBoundsException; it means you tried to access an invalid index. This would be one that is less than zero or greater than the max. As you correctly noted, 697 is the max index for an array of 698 items... so trying to access index 698 throws an exception.

Upvotes: 7

Related Questions