Recently during one of project, I was creating a map of integer and list of integer. My code snippet something like:-
I was expecting something like {1=(1), 2=(1,2 ), 3=(1,2,3), 4=(1,2,3,4), 5=(1,2,3,4,5), 6=(1,2,3,4,5,6), ...} as output. However, I was surprise to see the output as {1=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2=(already output), 3=(already output), 4=(already output), 5=(already output), ...}.
I was wondering what's wrong with my code and started exploring how I can fix it.
After going through blogs & docs, I get to know that if I call some method like clear() on a list and put it in a map and use the same variable with modified values for next element of map, ultimately SFDC stores address of same variable in each element of map, because of which I finally get same value in each element of map as per above code.
If I make a small change in my code,as shown below, my code will start yielding expected result:-
If you closely look into change, instead of using clear() method, in each iteration, I have used 'new List<integer>()', which make sure that SFDC assigns different addresses in each iteration and I am able to get expected value.
Related link http://blogs.developerforce.com/developer-relations/2012/05/passing-parameters-by-reference-and-by-value-in-apex.html
It was worth reading this blog. Quite intersting one. :)
ReplyDeleteThanks for the article Digamber. Lead me in the right direction to solve a problem.
ReplyDelete