0

I am getting subject line - error while I try to execute below apex code snippet

Apex Code Snippet

 for(Integer index = 0; index < surveyInstanceList.size(); index++) {
    Survey_Question_vod__c  sq = surveyInstanceList[index];
    if(sq.text_vod__c!=null) {
        If(Integer.valueof(sq.text_vod__c.split(' ')[1].left(1)) == count) {
            surveyInstanceListsorted.add(sq);  // This line throws error.
            count++;
        } else {
            // -- will step back one to process record that just moved in
            surveyInstanceList.add(surveyInstanceList.remove(index--));
               }
                             }
            } 
  • 1
    please add lines where you're initializing surveyInstanceListsorted and surveyInstanceList – Ilya Lepesh May 12 '16 at 3:26
  • for ex. if surveyInstanceList contains only 1 record and 1st for loop iteration it executes else part then what will happen .remove(index--) beacuse this time your index will be -1 – Ratan Paul May 12 '16 at 3:44
  • 2
    @Ratan you'd get a index out of bounds exception if that were the case. But you won't actually hit -1, because it's a postfix operator and the loop increment will ensure it will be at least 0. – sfdcfox May 12 '16 at 4:44
  • @sfdcfox so it if my index is 0 and If I use index--, It will take at least 0 not -1 ? interesting never looked into.. – Ratan Paul May 12 '16 at 4:57
  • 2
    @Ratan yes, because index 0 will be removed, then there variable index will update to -1, and then the index++ will execute immediately afterwards, so it will again be 0. – sfdcfox May 12 '16 at 5:02
3

If this is the line that is throwing the error:

surveyInstanceListsorted.add(sq); // This line throws error.

The most likely scenario is that ahead of this block of code which you're showing us you did not initialize this List<Survey_Question_vod__c> and you're trying to add an item to null:

surveyInstanceListsorted = new List<Survey_Question_vod__c>();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.