Java Notes: Deep vs. Shallow Copies

Assignment and copies

Assignment. The assignment operator (=) makes a copy of the "value". For a primitive type (int, double, etc) this simply copies the numeric value, but the assignment of a object copies only the reference (address in memory) of the object.

Sharing immutable objects

One object may have many references to it. If an object is immutable, ie can't be changed, it can safely be shared, and there is no reason to have more than one copy of it. The most common example of this is the String class. All string objects are immutable. This is very useful and is fast because there is no need to copy the contents of the string, but only the reference to it (typically 32 bits). If you need a mutable string, then you can use StringBuilder.

No way to tell if something is immutable

The careful reader of Java keywords may have noticed that there is a const keyword. Mysteriously, this keyword has no use. The intent was to use it to declare things to be unchangeable, but it turned out to be too hard to make this work in an absolutely safe manner. There is no way to know if objects of a class are immutable, except by reading the documentation.

The final keyword allows only one assignment to a variable, but doesn't protect the fields of the object that variable references.

Copying mutable objects

xxx

Copying an array

xxx

Shallow copies

xxx

Deep copies

xxx

Deep-enough copies

xxx

clone()

xxx