Câu 1
Trung bình
Một đáp án
Đoạn code sau in ra gì?
class Order implements Cloneable {
List<String> items = new ArrayList<>();
@Override
public Order clone() {
try {
return (Order) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
Order a = new Order();
a.items.add("book");
Order b = a.clone();
b.items.add("pen");
System.out.println(a.items);
Xem đáp án và giải thích
Object.clone() sao chép từng field: field kiểu reference chỉ được copy reference, nên hai object dùng chung list. Khi áp dụng Prototype cần tự sao chép sâu các field mutable (ví dụ copy.items = new ArrayList<>(items)). Nhiều team tránh Cloneable và dùng copy constructor hoặc static factory copyOf cho rõ ràng hơn.