0

I know List Index out of Bounds: positive num but I am getting List Index out of Bounds: -1 error. What does this mean ?

if(pnlNewYearsd.size() > 0) {
    startYear = pnlNewYearsd.get(0);
} else{
    if(startYear == '') {
    // getting error in below line 
    startYear = **temp_hop_id_list[(temp_hop_id_list.size()/2)-1].Year__c;**
    } else {
    startYear = temp_hop_id_list[temp_hop_id_list.size()-1].Year__c;
    }                      
}
  • 2
    It will be helpful for us if you can post some code and highlight the line where you are getting the error. – manjit5190 Nov 29 '16 at 12:07
  • @manjit_singh updated post – Srujan Nov 29 '16 at 12:36
  • 1
    If your list size is 1 your code will blow up at the time of (size()/2) - 1. This will result in a negative value and is more than likely why you are receiving index out of bounds. – TSmith Nov 29 '16 at 12:42
  • 1
    Your temp_hop_id_list list seems to have a size of 0. Add a condition to manage this case. – SF_user Nov 29 '16 at 12:49
1

You are running into this issue based on the size of your temp_hop_id_list. At the point of performing the division on list size your list size appears to be <= 1.

Here is some logic I have created to illustrate how you would recieve a List Index Out Of Bounds: -1 error.

List<Contact> emptyCons = new List<Contact>();

if(emptyCons.size() > 0) {
    system.debug('Woohoo');
} else {
    system.debug('Below is a List Index Out Of Bounds -1 error.');
    system.debug((cons.size()/2)-1);
}

Changes needed to your logic:

if(pnlNewYearsd.size() > 0) {
    startYear = pnlNewYearsd.get(0);
} else {
    if (temp_hop_id_list.size() >= 2) {
        startYear = startYear == '' ? temp_hop_id_list[(temp_hop_id_list.size()/2)-1].Year__c : temp_hop_id_list[temp_hop_id_list.size()-1].Year__c;
    } else {
        // Exception Handling
    }                    
}

Here you are making sure your list size is greater or equal than 2 to allow the division only ever end with a result of 0 or more.

I have also cleaned up all the if/else statements and used a ternary operator.

0

It means exactly what it says: you are trying to index the array at element -1. Caused by the expression between [ and ], meaning that temp_hop_id_list.size()/2 has a value of 0.

0

I think temp_hop_id_list.size() is of size 0 or 1 . You can add condition to handle this error.

if(think temp_hop_id_list.size()>=2) {
    startYear = temp_hop_id_list[(temp_hop_id_list.size()/2)-1].Year__c;
    } else {
    startYear = temp_hop_id_list[temp_hop_id_list.size()-1].Year__c;
    }  
}

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.