I am trying to wrap my head around this, as I am a Python programmer 90% of the time, and from time to time, write a few groovy programs. So here is my question to the groovy development community.
When I define a new groovy Map variable copied from an existing hubitat application state variable, it appears that this new copied Map variable is a Hashmap of the original state variable instead of a separate instance? When I modify the newly created copied Map variable (see below), both original state map variable (which I did not directly modify) and new map variable are now the same. My question, how do I create/copy/clone a new groovy Map variable from either an existing state variable so they are not linked?
For example, here is a snippet of a simplified code where I would like to filter/modify the copied Map variable to only keep certain map keys so I have the original (unmodified) and modified/filtered Map variables.
def originalMap = [1:"One",2:"Two",3:"Three",4:"Four"]
def filteredMap = originalMap // Copy the originalMap
def keepList = [1,3] // List of keys that I wish to keep in the new filteredMap
filteredMap.keySet().retainAll(keepList);
log.info (originalMap);
log.info (filteredMap);
**Results:**
[1:One, 3:Three]
[1:One, 3:Three]
This isn't a copy but rather just another reference to the same underlying object. To copy, among likely other possibilities, you can use the constructor that takes an existing Map as a paramter, e.g.,
def filteredMap = new HashMap(originalMap)
you could also use the clone() instance method:
def filteredMap = originalMap.clone()
(I think both are "shallow copies," but for the simple data types in your example and probably anything you'd be doing with the objects available to you in Hubitat, that will probably not matter...)
I am using the clone() option mentioned above in all my drivers so I can confirm that works for sure. I ran into a similar problem trying to copy one map to another and that was the solution I found.
For data types that can be represented with JSON, yes, but that's a roundabout way to make a copy (converting it to JSON and back instead of just dealing with the original data structure).