Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.
Hi,

I'm trying to use a map as a static set of values, something akin to a literal, and want to use different values for the 'literal' in different sections of code. What I would like to do is something like this:

Map<String,List<String>> x;

x = new Map<List<String>>{'key1' => new List<String>{'a', 'b', 'c'}, etc};

// stuff using x as list of literals

x = new Map<List<String>>{'key1' => new List<String>{'d', 'e', 'f'}, etc};

// stuff using x as list of different literals

now my question is how this will behave in apex - whether this will create a memory leak? when I instantiate the same map the second time, does the memory get freed from my first 'instance'? I haven't coded in 18 years, and that was in C where I had to be more explicit with my memory.

I could just create multiple Maps, but it seems unnecessary when each of these sets are used mutually exclusively, and i have a perfectly good Map sitting there already.

thanks in advance!
4 answers
  1. Jan 2, 2019, 12:43 PM
    Hi Alex,

    Your second X assignment will replace the first one. If you debug the values of x you will get d, e, f. Check out this code:

     

    Map<String,List<String>> x;

    x = new Map<String,List<String>>{'key1' => new List<String>{'a', 'b', 'c'}};

    // stuff using x as list of literals

    x = new Map<String,List<String>>{'key1' => new List<String>{'d', 'e', 'f'}};

    // stuff using x as list of different literals

    System.debug(x.values());

    // Will print: d, e, f

    I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

    Regards
Loading
0/9000