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,23 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Deliberately does not compile. Not part of the Maven build; scripts/broken.sh runs javac on it
|
||||
* and commits the compiler's own message to output/02-final-field-clone.txt.
|
||||
*
|
||||
* The point: a Cloneable class cannot deep-copy a final field inside clone(), because clone()
|
||||
* is not a constructor and final fields cannot be reassigned after construction.
|
||||
*/
|
||||
public class FinalFieldClone implements Cloneable {
|
||||
private final List<String> items = new ArrayList<>();
|
||||
|
||||
@Override public FinalFieldClone clone() {
|
||||
try {
|
||||
FinalFieldClone copy = (FinalFieldClone) super.clone();
|
||||
copy.items = new ArrayList<>(items); // error: cannot assign a value to final variable
|
||||
return copy;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user