Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created January 29, 2016 06:22
Show Gist options
  • Save nobeans/8aeabead2d8e906df8ac to your computer and use it in GitHub Desktop.
Save nobeans/8aeabead2d8e906df8ac to your computer and use it in GitHub Desktop.
Map単体のcloneだと項目の参照経由でmutableですよ
def map = [a: [1], b: [2], c: [3]]
println map.dump()
// clone()の場合、コストも気になるが実際影響が出るんだった!!!!!
def newMap = map.clone()
println newMap.dump()
// 追加した項目は独立であるが...
newMap.x = "XXXX"
assert newMap.x == "XXXX"
assert !map.containsKey('x')
// 既存項目では既存インスタンスが参照できるので状態を変更できてしまう
newMap.c << 999
assert newMap.c == [3, 999]
assert map.c == [3, 999] // !!!!!!!
//
def newMap2 = map.collectEntries { String key, value -> [key, value.clone()] }
println newMap2.dump()
newMap2.x = "XXXX"
assert newMap2.x == "XXXX"
assert !map.containsKey('x')
// 値もcloneしたので副作用はなくなる。が、コストは高い。
newMap2.c << 888
assert newMap2.c == [3, 999, 888]
assert map.c == [3, 999] //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment