1

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?

1 Answer 1

2

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>)
  json.deserialize(
    json.serialize(original),
    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.

3
  • 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
    Commented Jan 18, 2019 at 17:48
  • Just tried it and it seems inner inner classes also clone instead of passing by references using JSON serialization
    – smohyee
    Commented Jan 18, 2019 at 17:57
  • @smohyee JSON has limitations on the data types it supports, but yes, it will recursively clone everything it does support.
    – sfdcfox
    Commented Jan 18, 2019 at 17:58

You must log in to answer this question.

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