function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vishnu_SFDCVishnu_SFDC 

List Index out of bounds Error

Hello ,

Below is the code for which i am getting the error.
system.debug(slots.size());
for(Integer i =slots.size()-1;i>=0; i--)
      {
        system.debug(slots[i]);
        date d = Date.newinstance((slots[i].StartDateTime).year(),(slots[i].StartDateTime).month(),(slots[i].StartDateTime).day());
        for (event__c e : event)
        {
            system.debug(e);
            system.debug(today2);
            //date d2 = Date.newinstance((e.Start_Datetime__c).year(),(e.Start_Datetime__c).month(),(e.Start_Datetime__c).day());
            if(((slots[i].startDateTime<e.Start_Datetime__c && slots[i].StartDateTime.addminutes(apptmin)<e.Start_Datetime__c) || 
               (slots[i].startDateTime>e.End_Datetime__c && slots[i].startDateTime.addminutes(apptmin)>e.End_Datetime__c))   &&
                (e.Start_Datetime__c <=today2.addDays(6) && e.Start_DateTime__c >= today2.addDays(-1)))
            {
                
            }
            else
            {
                if(slots[i].userid == e.Event_Owner__c)
                {
                slots.remove(i);
                }
            }
      }
      }
When i debug the size i get size = 264.
but i get List index out of bounds: 263 error.
can someone help me out with this.

Thanks,
Vishnu

Jen BennettJen Bennett
Have you tried incrementing through the list?
for (i=0; i<slots.size();i++)?
Vishnu_SFDCVishnu_SFDC
yes. I didnt work.
It works in sandbox though.
Jen BennettJen Bennett
yeah it actually makes more sense to decrement the for loop, I think the problem is that you're removing the item for the list while you're inside the inner for loop.
Vishnu_SFDCVishnu_SFDC
Can you tell me a way how to remove outside of for loop?
Jen BennettJen Bennett
It depends on whether or not you want to remove the item if any event does not meet the criteria when the userid = ownerid or if all events need to not meet the criteria and belong to that user. If just one event needs to meet the criteria then you can leave it where you have it but add a break after the removal so it leaves the inner loop and stops checking the events.