1

I got a behavior I don't understand,

I'm instanciating a map with this method : Map> createMap2 (Integer nbAcc)

    Public static Map<Integer, List<Account>> createMap2 (Integer nbAcc) {
    Map<Integer, List<Account>> newMap = new Map<Integer, List<Account>> ();
    List<Account> accL = new List<Account>();


    for (Integer i = 0; i < nbAcc; i++) {
        // add datas
        accL.add(
                new Account(Name= i+'bonjour'+i));
        newMap.put(i, accL);
    }
    return newMap;
}

And my method is

    public static void testsSurMaps () {
    Map<Integer, List<Account>> myMap = createMap2(3);

    // debug de la map originale
    for(Integer nb : myMap.keySet()) {
        System.debug('M1[' + nb + '] : ' + myMap.get(nb));
    }

    Account copain = new Account(Name='YOLO à TOULOUSE');

    // THIS is where I don't understand
    myMap.get(0).add(copain);

    System.debug('\n\n\n');

    for(Integer nb : myMap.keySet()) {
        System.debug('Key is : ' + nb + '\nMap[' + nb + '] : ' + myMap.get(nb) + '\n');
    }

    // The account has been added to all the keyset ?!!
}

I can't understand why the newly created Account that I only want to add to the value corresponding to the key 0, is added to all the values.

The debug shows :

enter image description here

1 Answer 1

3

myMap.get(0) , myMap.get(1) and myMap.get(2) points to same instance of accL as you have only intialized accL once.

You for every new Map value, you have to create a new instance of accL

public static Map<Integer, List<Account>> createMap2 (Integer nbAcc) {

    for(Integer i=0 ; i < nbAcc ; i++){
        List<Account> accL = new List<Account>();
        for(Integer j= 0 ; j < nbAcc ; j++){
            accL.add(
                    new Account(Name= j+'bonjour'+j));
        }
        accL.put(i , accL);


    }
     return newMap;
}
3
  • Wow ! Ok, thanks for this ! So, is there a way to indicate that I don't want the reference to be passed, but only the values of the list ? Something from : newMap.put(i, accL); To newMap.put(i, accL.values); ? Commented Aug 1, 2019 at 16:54
  • 2
    how aboute accL.clone() ? Commented Aug 1, 2019 at 16:55
  • Great ! Thanks, I still have a lot to learn ;) Commented Aug 1, 2019 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .