Cloneable
A marker interface that allows Object.clone(). New code uses copy constructors instead.
Available since: Java 1.0
Syntax
public interface CloneableExamples
clone() on an array is an easy way to copy it:
void main() {
int[] a = {1, 2, 3};
int[] b = a.clone();
b[0] = 99;
IO.println(Arrays.toString(a) + " " + Arrays.toString(b));
}Output:
[1, 2, 3] [99, 2, 3]A copy constructor instead of Cloneable:
class Cart {
final List<String> items;
Cart() {
items = new ArrayList<>();
}
Cart(Cart other) {
items = new ArrayList<>(other.items);
}
}
void main() {
var cart = new Cart();
cart.items.add("milk");
var copy = new Cart(cart);
copy.items.add("bread");
IO.println(cart.items + " " + copy.items);
}Output:
[milk] [milk, bread]Notes
Cloneable has no methods at all: it only allows Object.clone(), which throws CloneNotSupportedException in a class without this interface. clone() makes a shallow copy, is awkward to override and does not work well with final fields — so for your own classes a copy constructor or a copyOf() factory is better. For arrays clone() works without caveats.
See also
- Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
- record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
Related recipes
In the tutorial
- Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.