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
Alex.AcostaAlex.Acosta 

IF Condition Bug?

I'm having some issue with some code and this seems like some sort of bug, can anyone explain to me why this is happening?

 

Map<String, List<String>> stringMap = new Map<String, List<String>>();
stringMap.put('key1', new List<String>{'value1', 'value2'});

for(String mapKey :stringMap.keySet()){
	for(Integer i = 0; i <= stringMap.get(mapKey).size(); i++){

		if(stringMap.get(mapKey).size() > i){
			system.debug(stringMap.get(mapKey).get(i));
		}

		if(stringMap.get(mapKey).size() > i++){
			system.debug(stringMap.get(mapKey).get(i));
		}

                /**
                 * CODE BREAKS ON THIS IF CONDITION 
                 * WHICH IT SHOULD FAIL TO VALIDATE... 
                 * stringMap.get(mapKey).size() = 2
                 * i++ = 2
* This IF condition should not pass. **/ if(stringMap.get(mapKey).size() > i++){ system.debug(stringMap.get(mapKey).get(i)); } } }

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

++ after a variable is a "postfix" operator. In other words, it occurs after the rest of the statement is evaluated. This means your code looks like this:

 

if(stringmap.get(mapkey).size() > i++) { // size() is 2, i is 1
// i is NOW 2
  system.debug(stringmap.get(mapkey).get(i)); // index 2 not valid.

Instead, use the less commonly used ++i notation:

 

if(stringmap.get(mapkey).size() > ++i) { // size() is 2, i is 2!
// not executed...

 

All Answers

sfdcfoxsfdcfox

++ after a variable is a "postfix" operator. In other words, it occurs after the rest of the statement is evaluated. This means your code looks like this:

 

if(stringmap.get(mapkey).size() > i++) { // size() is 2, i is 1
// i is NOW 2
  system.debug(stringmap.get(mapkey).get(i)); // index 2 not valid.

Instead, use the less commonly used ++i notation:

 

if(stringmap.get(mapkey).size() > ++i) { // size() is 2, i is 2!
// not executed...

 

This was selected as the best answer
Alex.AcostaAlex.Acosta

Thanks, I did not know that.