-1

For the following code I am getting an index out of bounds exception and I am not sure as to why. Any help is greatly appreciated.

public Rabbit nearestRabbit()
{
    List<Rabbit> rabbits = this.getWorld().getObjects(Rabbit.class);
    if (this.getWorld().getObjects(Rabbit.class) == null)
    {
        return null;
    }
    Rabbit nearest = rabbits.get(0);
    double distance = distanceTo(nearest);

    for (Rabbit rabbit : rabbits)
    {
        double thisDistance = distanceTo(rabbit);
        if (thisDistance > distance)
        {
            distance = thisDistance;
            nearest = rabbit;
        }
    }
    return nearest; //@@@@@@@
}
jane d
  • 1
  • 2

4 Answers4

4

This is mainly due to your list size, I know that you have checked null for the list but since the list is not null it can still be empty with the size 0 and you can not access to the element at index 0. I recommend you to check the list size.

talex
  • 17,973
  • 3
  • 29
  • 66
Harpurest
  • 41
  • 3
2

You are getting this exception by not checking if the index is in bounds in the call rabbits.get(0).

A simple workaround is to put this code first.

if (rabbits.isEmpty())
    return null;

This checks if the list is empty before making any other calls.

Also, it would be best to refrain from reference this.getWorld().getObjects(Rabbit.class) more than once, especially after holding it as a variable which is much more accessible.

1

Add a size check to your if

if (this.getWorld().getObjects(Rabbit.class) == null || rabbits.isEmpty() )

A list may well not be null yet still be empty. E.g. any freshly generated one:

LinkedList<Object> objs = new LinkedList<>();
System.out.println(objs != null && objs.isEmpty()); //true
nitowa
  • 1,079
  • 2
  • 9
  • 21
0

Your IndexOutOfBound is probably when you are getting element at index 0 where the list might be empty.

if (!rabbits.isEmpty())
{
    Rabbit nearest = rabbits.get(0);
}