index out of bounds exception java

Paul Angelo Pines Cabrera picture Paul Angelo Pines Cabrera · Mar 17, 2013 · Viewed 76.7k times · Source

So the error message is this:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at FcfsScheduler.sortArrival(FcfsScheduler.java:77)
at FcfsScheduler.computeSchedule(FcfsScheduler.java:30)
at ScheduleDisks.main(ScheduleDisks.java:33)

with my code as

public void sortArrival(List<Request> r)
{
    int pointer = 0;
    int sProof = 0;
    while(true)
    {
        if(r.get(pointer).getArrivalTime()<r.get(pointer+1).getArrivalTime())
        {
            Request r1 = r.get(pointer);
            Request r2 = r.get(pointer+1);
            r.set(pointer, r2);
            r.set(pointer+1, r1);
        }
        else
        {
            sProof++;
        }
        ++pointer;
        if(pointer>r.size()-2)
        {
            pointer=0;
            sProof=0;
        }
        if(sProof>=r.size()-2)
        {
            break;
        }
    }
}

The error is at

if(r.get(pointer).getArrivalTime()<r.get(pointer+1).getArrivalTime())

but I think the array index is checked ok with the code after the increment of pointer. Is it an array out of bounds exception or something else? Normally, the error is ArrayIndexOutOfBoundsException when it is the array. What seems to be the problem here?

Answer

Ajay S picture Ajay S · Mar 17, 2013

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

ArrayList is empty. It does not contain any element.

Index: 0, Size: 0.

You are trying to access it.So you are getting IndexOutOfBoundsException.

if(r.size() == 0) && r.size() < pointer + 1)   //If ArrayList size is zero then simply return from method.
  return;