In Java, the `clone()` method is used to create a duplicate of an object. However, its usage is often discouraged due to potential issues with shallow copies, type safety, and code readability. When an object is cloned, the default implementation of `clone()` creates a shallow copy, meaning it copies the object's fields but not the objects they reference. This can lead to unintended side effects when modifying mutable objects. Therefore, it's essential to understand the implications of using `clone()` and consider alternative approaches like copy constructors or factory methods.
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
try {
Person original = new Person("John", 30);
Person copy = (Person) original.clone();
System.out.println(original != copy); // true, different instances
System.out.println(original.name.equals(copy.name)); // true, same name
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?