I've created a class of a custom datatype:
public class KPI {
public String name { get; set; }
public Decimal target { get; set; }
public Decimal actual { get; set; }
public Decimal percentage { get; set; }
public KPI (String name, Decimal target, Decimal actual) {
this.name = name;
this.target = target;
this.actual = actual;
this.percentage = (target > 0 && actual > 0) ? (actual / target) * 100 : 0;
}
}
I have a function that is generating a List of this empty data type:
public static Map<Id, List<KPI>> CreateMapUserIdToKPIList() {
List<KPI> kpiList = new List<KPI>();
for (KPI_Setting__c kpiSetting : kpiSettingList) {
kpiList.add(new KPI(kpiSetting.Name__c, 0.00, 0.00));
}
Map<Id, List<KPI>> mapUserIdToKPIList = new Map<Id, List<KPI>>();
for (Id userId : userMap.keySet()) {
mapUserIdToKPIList.put(userId, kpiList.clone());
}
return mapUserIdToKPIList;
}
However, when I iterate through the Map and the mapped List any changes made to one List is effecting the all List collections in the map. I know this is because the List<KPI>
is referencing the original, empty List.
When I do the following, changes made to one List doesn't affect them all:
public static Map<Id, List<KPI>> CreateMapUserIdToKPIList() {
Map<Id, List<KPI>> mapUserIdToKPIList = new Map<Id, List<KPI>>();
for (Id userId : userMap.keySet()) {
List<KPI> kpiList = new List<KPI>();
for (KPI_Setting__c kpiSetting : kpiSettingList) {
kpiList.add(new KPI(kpiSetting.Name__c, 0.00, 0.00));
}
mapUserIdToKPIList.put(userId, kpiList);
}
return mapUserIdToKPIList;
}
However, this seems really inefficient to loop through each user and in that loop, loop through another collection generating the same values that have been generated before.
I've tried, instead of using kpiList.clone()
things like new List<KPI>(kpiList)
but that too references the initial list. I can't use deepClone()
as I'm getting an error stating deepClone
can only be used on sObject types.
Is there a way to "deepClone()
" a custom datatype List?