2

This simple method I wrote is an attempt to mimic the equivalent iterative method (I'm just curious about recursion in Apex). It must return the element of a list of custom objects that have the older Createddate.

I printed head and current list value for each recursion layer and the result is correct, but returning to the caller I had a "List out of bounds" error. Since base cases are covered, which further step do I need to do to avoid this error?

Let the size of COset = n, the index in which I got the error is always n-1.

public static customer_Obj__c solveQueueRic(List<customer_Obj__c> COset,Integer index,customer_Obj__c head){
        customer_Obj__c lg = COset[index];
        if(index == 0){
            head = lg;
            return solveQueueRic(COset,index+1,head);
        }
        if(index < COset.size()){
            if(lg.Createddate < COset[index].Createddate){
                head = lg;
            }
            return solveQueueRic(COset,index+1,head);
        }
        return head;
    }
2
  • Why don't you do this directly with soql query or a for-loop?? p.s: i can't yet write a comment.
    – Mo Hamada
    Apr 24, 2019 at 8:49
  • Because the list size counts a lot of records I use a method to filter them and then put each category in a list. Then for each list I call this method to have, for each category, the value I want. Your solution tryes to ignore recursion also, since the loop itself is a iterative paradigm. Apr 24, 2019 at 8:53

1 Answer 1

3

You are getting this error because of this below line

customer_Obj__c lg = COset[index];

Lets say, size of COset is 4 i.e. you can go upto index 3, so when your code goes into recursion and when index reaches 4, it is bound to give you List index out of bound exception as there won't be any element at index 4 as size of your list is 4.

You can instead, move that above line inside your condition something like below

public static customer_Obj__c solveQueueRic(List<customer_Obj__c> COset,Integer index,customer_Obj__c head){
    customer_Obj__c lg;
    if(index == 0){
        lg = COset[index];
        head = lg;
        return solveQueueRic(COset,index+1,head);
    }
    if(index < COset.size()){
        lg = COset[index];
        if(lg.Createddate < COset[index].Createddate){
            head = lg;
        }
        return solveQueueRic(COset,index+1,head);
    }
    return head;
}
1
  • Damn, embarrassing moment here. Thank you Vijay! Apr 24, 2019 at 8:59

You must log in to answer this question.

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