+ Start a Discussion
Sylvio AvillaSylvio Avilla 

List index out of bounds: -1 (List is not empty!)

Hello everyone,

Bellow is part of a code and I would like to know if someone could tell me why I’m receiving the error "List index out of bounds: -1"  for po.Interval2__c even though po.Size__c = 4 ( if I delete line po.Interval2__c =myValues[myValues.size()-2]; code runs ok )
 
List<Integer> myValues = new List<Integer>();
            myValues.add(myValue);
            (myValues.sort());
            
          	        
            po.Interval1__c = myValues[myValues.size()-1];
            po.Interval2__c =myValues[myValues.size()-2];
            po.Size__c = myValues.size();

Thanks

Sylvio
Best Answer chosen by Sylvio Avilla
brahmaji tammanabrahmaji tammana
Hi Sylvio,

I see there is something wrong in this code.
If the list has only one element, you will get this error. PFB the step by step explanation.
 
List<Integer> myValues = new List<Integer>(); //List Created
            myValues.add(myValue); //Added one value, so the size of the list will be 1
            (myValues.sort()); //Sorted
            
            po.Interval1__c = myValues[myValues.size()-1]; // Accessing the first value
// size of the list is 1 and subtracting 1 so you will get myValues[0] and you get the value
            po.Interval2__c =myValues[myValues.size()-2]; // Here also size =1, and subtracting 2 myValues[1-2] = //myValues[-1] -- This is not correct
            po.Size__c = myValues.size();


Thanks

Brahma

All Answers

brahmaji tammanabrahmaji tammana
Hi Sylvio,

I see there is something wrong in this code.
If the list has only one element, you will get this error. PFB the step by step explanation.
 
List<Integer> myValues = new List<Integer>(); //List Created
            myValues.add(myValue); //Added one value, so the size of the list will be 1
            (myValues.sort()); //Sorted
            
            po.Interval1__c = myValues[myValues.size()-1]; // Accessing the first value
// size of the list is 1 and subtracting 1 so you will get myValues[0] and you get the value
            po.Interval2__c =myValues[myValues.size()-2]; // Here also size =1, and subtracting 2 myValues[1-2] = //myValues[-1] -- This is not correct
            po.Size__c = myValues.size();


Thanks

Brahma

This was selected as the best answer
Sylvio AvillaSylvio Avilla
Thanks Brahma,

I found the error. In my complete code, this function was inside a LOOP... so, the part :
 
po.Interval1__c = myValues[myValues.size()-1];
 po.Interval2__c =myValues[myValues.size()-2];
 po.Size__c = myValues.size();
Should be outside....

Thank you again