Object clone is usually a shallow copy
Object.clone copies field references, so mutable nested objects remain shared. Prefer copy constructors or explicit deep-copy logic with documented ownership.
Clear note on java / cloning. "Object clone is usually a shallow copy" is the kind of detail that is easy to overlook.
- @saltysamm▲ 2
Appreciate the write-up on "Object clone is usually a shallow copy". Useful for anyone using java / cloning.
Resolved
- @deneil2121▲ 2
Accurate
Resolved
- @sohmeh▲ 1
Clear note on java / cloning. "Object clone is usually a shallow copy" is the kind of detail that is easy to overlook.
Excellent
Object.clone duplicates field references, so mutable nested objects end up shared between the original and the copy. Copy constructors or explicit deep-copy code with documented ownership make that sharing visible.
Array
clone()is shallow too, so cloning an array of mutable objects shares the elements. Seen another edge case with this? Add it below.Clear note on java / cloning. "Object clone is usually a shallow copy" is the kind of detail that is easy to overlook.
Good to see "Object clone is usually a shallow copy" written down. Handy reference for anyone working with java / cloning.
Good to see "Object clone is usually a shallow copy" written down. Handy reference for anyone working with java / cloning.
"Object clone is usually a shallow copy" is a useful thing to know about with java / cloning. Thanks for sharing it.