I'm trying to fill a Map < Id, List< sObject>> by looping other the Map.keySet(), filling the list of sObjects, affecting it, and then go to the next key.
I read somewhere that it was a good practise to instanciate my temporaryList once before looping, begin to loop : filling it, affecting it the the Map.get(key), and then clearing it after use (to be able continue treatment).
Something like this :
// instanciating once a tempList
List<sObject> tempList = new List<sObject>();
for(Id id : Map.keySet()) {
for(sObject obj : anotherList) {
tempList.add(obj);
}
// then add to the Map as value for the actual
// if not deepCloning, it's erased two lines after ... (or I may miss something )
Map.put(id, tempList.deepClone());
tempList.clear();
}
I did it and first got a problem because of the passing by reference, so I used list.deepClone() and it went well.. I mean after filling my tempList and affecting it to the Map.get(key), clearing the tempList also clear the Map.get(key) and that, of course, wasn't what I was trying to do.
Naturally, that would not be my first way of doing it, I'll do it like this :
For(Id id : Map.keySet()) {
// declaring here the List to fill
List<sObject> tempList = new List<sObject> ();
for(sObject obj : anotherList) {
tempList.add(obj);
}
// then add to the Map as value for the actual key
Map.put(id, tempList);
}
But it's on the first hand only, within a loop, a declaration of a new List<> On the other hand, instanciating it before loops, using it, deepcloning the list to feed the Map.values(), and then clearing it to be able to use it for the next key in map.keySet() we have to fill...
Is really the second method the best ? I got some issues understanding every aspect of POO references passing