Painless Map copies are painful

I'm trying to create a map of maps.
so the map is like ['one':map,'two':map,'three':map,...]
all of the maps inside the map are identical.
so I want to create an insideMap and just use that to define the mainmap

ie:
Map insideMap = ['inside':1,'inside2':2];
Map outsideMap = ['one':insideMap,'two':insideMap];

but i'm finding that when i update ie outsideMap.one.inside, it updates at the same time outsideMap.two.inside with the same value? how do I do this without just having to create the whole map?

ie: I don't want to do this because this is just an example, and its a script so there's only so much room:
Map outsideMap = ['one':['inside':1,'inside2':2],'two':['inside':1,'inside2':2]];

I would be curious to hear about the entire use case for this. As far as deep-copying Maps in Painless, this will need to be done by hand because there's no simple way to be able to guarantee a deep-copy of all the key-value pairs in the Map depending on what the data is. Java would suffer from the same difficulties as there is no magic bullet for this particular problem.

Painless does however support functions and it would be possible to write a single function to deep-copy the Maps in questions for your specific script. Something like the following:

  Map deepCopyMap(Map original)  {
    Map copy = new HashMap();

    for (def originalKey : original.keySet()) {
      def originalValue = original.get(originalKey);

      def copyKey = // logic to deep copy originalKey
      def copyValue = // logic to deep copy originalValue

      copy.put(copyKey, copyValue);
    }

    return copy;
  }

  Map insideMap = ['inside':1,'inside2':2];
  Map outsideMap = ['one':insideMap,'two':deepCopyMap(insideMap)];

So instead i created a function that returned the map for duplication and all is well.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.