You need to sign in to do that
Don't have an account?
Problem with list.add() method
Here I am iterating through a loop and creating several instance of an sObject and adding it to a list.
for(AggregateResult sa : salesActualList)
{
ForecastSummary forecastItems = new ForecastSummary();
forecastItems.RSC_Id = (Id) sa.get('RSC_Id');
forecastItems.RSC_Code = (String) sa.get('RSC_Code');
forecastItemsList.add(forecastItems);
}
Finally the list contains only the last added record inserted 'n' no.of times.
When I debug inside the for loop it shows all the records. I am wondering why this is happening.
There is no issue with the declaration here as it is declared as a class variable.
Appreciate your help.
What error message are you getting on the list.add() line?
Alex there is no runtime or complie error. Its just that it stores only the duplicate of last added record.
The code looks right to me, but I may be missing something.
Maybe the problem lies with how you are reading back the list after you populate it? Could you take another look at that code or paste it here maybe?
When I debug the list I get this.
01:17:20.580|USER_DEBUG|[437]|DEBUG|forecastItemsList -- (VFCtrl_Forecast_Calculation.ForecastSummary:[ RSC_Id=a01M0000000EhWyIAK, RSC_code=16], (already output), (already output), (already output))
The method returns the list to a visual force page where I get the duplicate records displayed.
Well, then, if my assumptions are correct, I have no idea how that "(already output)" thing got there. And you say that when you loop through and print it out, they show the same value as the first element? How odd.
My guess is that all of those are pointing to the same sObject in memory. But according to your code, that shouldn't be true.
Anyone else have any interpretations of this debug statement?
Poor me. It was a programming error as you said those are pointing to the same sObject in memory.
Thanks alex for your time.
Hi,
I was hoping you might be able to articulate your programming error a bit more explicitly. I have seen this from time to time and have been able to work around it. But, honestly, I do not know the direct way to correct it.
Thank you.
Actually, I just figured it out. I was creating an instance of a temp sObject that I would populate and then add to my List within a loop. However, I was creating that instance of the temp outside of the loop. In other words, I was not actually creating a new instance for each iteration of my loop. Thus, every element of my list was pointing to that one single temp sObject, and would obviously give the result of having every element of the List equal to the last one added.
let's say your code includes ...
list<sObject_Whatever> newChecks = new list<sObject_Whatever>();
where you might have used the following in your code:
newChecks.clear();
replace the .clear() statement with:
newChecks = new list<sObject_Whatever>();
Then all is fixed