Sunday 27 January 2019

Groovy: Clone map


'clone()' method is used to get the copy of a map.

HelloWorld.groovy

def map1 = [
 simpleType : 123,
 complexType : [a : 1, b : 2],
 boolType : true,
]

def map2 = map1.clone()

println "Elements of map1 are"
printMap(map1)

println "\nElements of map2 are"
printMap(map2)

void printMap(map){
 map.each { entry ->
  println "key: $entry.key, value: $entry.value"
 }
}

Output
Elements of map1 are
key: simpleType value: 123
key: complexType value: [a:1, b:2]
key: boolType value: true

Elements of map2 are
key: simpleType value: 123
key: complexType value: [a:1, b:2]
key: boolType value: true


'clone' method returns a shallow copy. If you would like to know more about shallow copy, I would recommend you to go through my below tutorial.


HelloWorld.groovy

def map1 = [
 simpleType : 123,
 complexType : [a : 1, b : 2],
 boolType : true,
]

def map2 = map1.clone()

println "Elements of map1 are"
printMap(map1)

println "\nElements of map2 are"
printMap(map2)

println "\nAdding two more keys to the map\n"

map2.get('complexType').put('c', 13)
map2.get('complexType').put('d', 14)

println "Elements of map1 are"
printMap(map1)

println "\nElements of map2 are"
printMap(map2)

void printMap(map){
 map.each { entry ->
  println "key: $entry.key, value: $entry.value"
 }
}

Output
Elements of map1 are
key: simpleType, value: 123
key: complexType, value: [a:1, b:2]
key: boolType, value: true

Elements of map2 are
key: simpleType, value: 123
key: complexType, value: [a:1, b:2]
key: boolType, value: true

Adding two more keys to the map

Elements of map1 are
key: simpleType, value: 123
key: complexType, value: [a:1, b:2, c:13, d:14]
key: boolType, value: true

Elements of map2 are
key: simpleType, value: 123
key: complexType, value: [a:1, b:2, c:13, d:14]
key: boolType, value: true

As you see the final output, Since clone method performs shallow copy, updates done to the complexType of map2 object are reflected to map1 also.




Previous                                                 Next                                                 Home

No comments:

Post a Comment