0

Getting List Index out of bounds error even after null check. below sample workable code.

Apex Demo Code

   String order = 'asc';
   String usrId = '<userid>';
   String query = 'SELECT Id, Name FROM Opportunity WHERE OwnerId =: usrId Order By Name '+order;
   List<Opportunity> oppManOwner = database.query(query );
   List<Opportunity> oppFiltered = new List<Opportunity>();

   Integer maxRecNo = 15;
   Integer pageNumber =3;

   Integer indexStart = (pageNumber*maxRecNo) - (maxRecNo);

   for(integer i=0; i< maxRecNo; i++){
      if(oppManOwner[indexStart] != null){ // List index getting out of bounds 
        oppFiltered.add(oppManOwner[indexStart++]);
      }
      else
        break;
    }

In Page number 3 less than 15 records are left. So when it reaches that point I assume
oppManOwner[indexStart] != null will break the loop, but still giving the List Index out of bounds error. What is going wrong here?

2 Answers 2

3

In a list, you can only access indices between 0 to List.size()-1 inclusive. Attempts to go outside this limit result in this exception. The more appropriate check would be:

  if(oppManOwner.size() > indexStart) {

An even better way would be to simply limit the loop to those items to begin with:

for(Integer i = (pageNumber-1)*maxRecNo, s = Math.min(pageNumber*maxRecNo, oppManOwner.size()); i < s; i++) {
  oppFiltered.add(oppManOwner[i]);
}
1
  • Thanks. I should have known the exception will throw when going out.
    – Brav
    Commented Mar 8, 2020 at 14:44
0

Your list may not have the record available at that index. You need to make sure to get from the list only if there is an element available at that index. Put a check to validate if the list size has records at the mentioned index. something like should help -

if(oppManOwner.size() > indexStart) { 
     if(oppManOwner[indexStart] != null){ 
        oppFiltered.add(oppManOwner[indexStart++]);
      }
      else
        break;
}
2
  • 1
    This code will also encounter the same error. It is not valid to access List[list.size()], as the last element is list.size()-1. It should be > instead of >= in this case.
    – sfdcfox
    Commented Mar 8, 2020 at 12:55
  • Thank.I have updated the answer. The check should always be a > and not >= . This should avoid the problem
    – Samir
    Commented Mar 8, 2020 at 12:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .