Created
January 29, 2016 06:22
-
-
Save nobeans/8aeabead2d8e906df8ac to your computer and use it in GitHub Desktop.
Map単体のcloneだと項目の参照経由でmutableですよ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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