copying: deep vs shallow copy module (clone() traps, copy constructors, serialization copy, records, defensive copies, collection copies), 17 contract tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4X2xx7RrveVQU9R1N
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
== 1. clone() does not call a constructor, and it is shallow ==
|
||||
Team constructor ran for 'platform'
|
||||
b == a : false
|
||||
b.members == a.members : true
|
||||
after a.members.add("meera"), b.members = [asha, ravi, meera]
|
||||
|
||||
== 2. The fix: copy the mutable field inside clone() ==
|
||||
c.members = [asha, ravi, meera]
|
||||
d.members = [asha, ravi]
|
||||
|
||||
== 3. Calling super.clone() without implementing Cloneable ==
|
||||
CloneNotSupportedException: com.ankurm.copying.CloneDemo$ForgotCloneable
|
||||
|
||||
== 4. Array clone() is shallow for nested arrays ==
|
||||
gridCopy[0] == grid[0] : true
|
||||
grid = [[99, 2], [3, 4]]
|
||||
gridCopy = [[99, 2], [3, 4]]
|
||||
|
||||
== 5. ArrayList.clone() is shallow too ==
|
||||
original.get(0) = abc-changed
|
||||
same element object: true
|
||||
|
||||
== 6. A parent clone() that uses 'new' breaks every subclass ==
|
||||
ClassCastException: class com.ankurm.copying.CloneDemo$Animal cannot be cast to class com.ankurm.copying.CloneDemo$Dog (com.ankurm.copying.CloneDemo$Animal and com.ankurm.copying.CloneDemo$Dog are in unnamed module of loader 'app')
|
||||
Reference in New Issue
Block a user