Can Java ArrayList be empty and indexOf is index 0?

I have the following segment of code in Java for Android:

int index = oldArray.indexOf(person);
if (index == -1) {
    Log.d("Tag", "TESI index == -1");
}
else {
    oldArray.remove(index);  <--- error is here
    newArray.add(person);
}

      

I got the following exception

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at com.tesi.salus.PersonView.updatePerson(PersonView.java:406) [line 406 is the remove]

      

My question is how is this possible?

If I understand well, if oldArray

empty, then it index

should be -1, not 0.

Or am I missing something?

Thank.

==================

Thanks for answers.

I only have one thread.

oldArray

is declared as:

public ArrayList oldArray<Person>;

      

And initialized below:

oldArray = new ArrayList();

      

+3


source to share


1 answer


if the object is null it will find the index null (which is zero in the empty list)



add nullcheck and it should work

0


source







All Articles