Index out of bounds

Hi everyone,
I’m hoping I’m missing something simple here. I want to display an object (which works) and when my player entity collides with this object the object should disappear. My collision code works but once the collision occurs my game crashes giving me this error:
IndexOutOfBoundsException: Index: 0, Size: 0
As far as I can tell there is an element in my array list at index 0. Can anyone please point out what I’m missing?

thanks!

ArrayList<Test> testList = new ArrayList(); //creates arrayList

void setup()
{
	testList.add(new Test((0, 0, 60)); //adds element to arrayList
}

void draw()
{
	testList.get(0).showList(); 
  	if (testList.get(0).testHit()) //this has been set to return true
  	{
  		testList.clear(); //clears arrayList and screen
  	}
}

After clearing the list is empty

Therefore you cannot access get(0) because 0 would be the first element but it does not exist

Size is 0

You can avoid the error by using if (…size() > 0) before the line

Or by setting a variable youLost to true

Alternatively call method isEmpty() and use the unary logical operator !:
https://docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#isEmpty()

if (!testList.isEmpty()) {
  final Test t = testList.get(0);
  t.showList();
  if (t.testHit())  t.clear();
}

Thank you! This has resolved my issue and I realise my mistake. I can finally move on :smile:

Thanks for the response Chrisir, this has worked wonders and I can now progress on my project

1 Like