0

I'm getting an outofbounds exception from the following code:

myArray.get(myArray.size() -  1)

I know it's due to the fact that myArray contains no items. I tried adding this before checking for the last added item in the array:

If (myArray.size()  == -1){ myArray.add(string) } 

But that didn't make any difference. What am I doing wrong?

1
  • 3
    Why do you think size() returns -1 when it's empty? Commented Apr 10, 2014 at 23:03

2 Answers 2

2

Try to use

if (!myArray.isEmpty())
    myArray.get(myArray.size() -  1);

This will get the last value in the list, when the list isn't empty.

Sign up to request clarification or add additional context in comments.

Comments

1

myArray.size() will never be -1. Note that size is a non-negative number. It can be 0 or more.

You can check if it equals 0 and then add element.

2 Comments

I was under the impression that the first position in the array is 0, that's why I was checking for -1.
@Josh The first position in the array is 0, but the numbering scheme of the elements has no bearing on the total number of elements. The size of an empty array is 0 because there are 0 things in it. End of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.