I have a map<string, InnerClass>, where the inner apex class containing no sObjects, just a bunch of simple variable types like booleans, integers and strings. (It also contains another inner class which also has only simple variable types, but I assume that doesn't matter).

My goal is to clone this map several times, putting different values in the WrapperClass properties for each map. I'm currently using the map clone() method.

Problem appears to be that when I'm updating the values on my latest clone, all the previously cloned maps update their values the same way. In other words, it appears that the clone() method only passed a reference to the existing WrapperClass object, rather than cloning it.

I know deepclone() would solve this problem, but it is only designed for sObjects. How can I clone my map in such a way that new copies of my inner classes are created for each map?


In Apex, you can either use JSON, make duplicates while you're creating the map, or write your own clone method.

Here's the JSON method:

map<string, InnerClass> clonedCopy = (map<string, InnerClass>)
    map<string, InnerClass>.class

This is as about as efficient as you think it is (hint: not at all).

If possible, consider just making duplicate values in your original method while creating the InnerClass objects, as this would be the most efficient method.

| improve this answer | |
  • Thanks fox! Do you know if having a different inner class stored as a variable within InnerClass will present any issues for the JSON method? – smohyee Jan 18 '19 at 17:48
  • Just tried it and it seems inner inner classes also clone instead of passing by references using JSON serialization – smohyee Jan 18 '19 at 17:57
  • @smohyee JSON has limitations on the data types it supports, but yes, it will recursively clone everything it does support. – sfdcfox Jan 18 '19 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.