Video in progress
What problems does Object.clone() have, and what's better to use for copying?
clone() doesn't call a constructor, makes a shallow copy by default, Cloneable is an odd marker with no method, and it doesn't get along with final fields either. A copy constructor or a static factory is simpler and safer.
📖 Answer
The classic bug is the shallow copy:
class Order implements Cloneable {
List<Item> items = new ArrayList<>();
@Override public Order clone() {
try { return (Order) super.clone(); }
catch (CloneNotSupportedException e) { throw new AssertionError(e); }
}
}
Order copy = original.clone();
copy.items.add(newItem); // it was added to original too: it's one list
Its other problems:
- the
Cloneableinterface has noclonemethod: it only changes the behavior ofObject.clone; - for a deep copy you have to reassign the field, which isn't possible with a
finalfield; - the constructor isn't called, so its invariant checks don't run;
- if a subclass doesn't override
clone, it ends up relying on the parent class's logic.
Instead:
public Order(Order other) {
this.id = other.id;
this.items = new ArrayList<>(other.items); // as deep as needed
}
// or
public static Order copyOf(Order other) { ... }
The best option is not needing a copy at all: an immutable object (a record, List.copyOf) can be shared freely. For arrays, though, array.clone() is fine and fast: it's the one good use of clone.
Sign up to mark studied questions and save your progress.