Adding/Removing elements from Collection classes on current iteration data

LIST
The list will not directly allow adding/remove elements on the current iteration. Below code will throw an exception:
Example:1
List<Integer> intNummbers = new List<Integer>{12,13};
for(Integer numbers : intNummbers)
{
    intNummbers.add(0,49);
}
System.debug('--'+intNummbers);


SET & MAP: 
These classes will allow us to add/remove elements on the current iteration.
Example: 2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Map<Integer,Integer> intMap = new Map<Integer,Integer>{};
  intMap.put(1,1);
  intMap.put(2,2);
  intMap.put(3,3);
   
for(Integer intval : intMap.values())
{
    intMap.put(4,4);        
}
System.debug('--- '+intMap);
Here is the output:
16:15:23:004 USER_DEBUG [10]|DEBUG|--- {1=1, 2=2, 3=3, 4=4}
Similarly, we can also modify keys
Example:3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Map<Integer,Integer> intMap = new Map<Integer,Integer>{};
  intMap.put(1,1);
  intMap.put(2,2);
  intMap.put(3,3);
   
for(Integer intval : intMap.keySet())
{
    intMap.put(4,4);        
}
System.debug('--- '+intMap);
output remains the same, as above:
16:15:23:004 USER_DEBUG [10]|DEBUG|--- {1=1, 2=2, 3=3, 4=4}

Adding elements to the current iteration set
Example:4
1
2
3
4
5
6
set<Integer> intSet = new set<Integer>{1,2,3};
for(Integer intval : intSet)
{
    intSet.add(4);
}
System.debug('--- '+intSet);
here is the output:
16:25:49:004 USER_DEBUG [6]|DEBUG|--- {1, 2, 3, 4}

For Array also, we can add elements to the current iteration data, below example explains the same:
Example:5
Integer[] intArray= new Integer[]{13,34};
for(Integer a: intArray)
{   
    intArray[1] =33; 
}
System.debug('--- '+intArray);

Note: Trigger.new is also a list but while iterating, apex runtime engine will allow. To conclude this post, we can say Example2,3,4,5 are exceptional cases. I don't see anywhere more information about these design decisions.

tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝

Comments