How does deep copies (clones) of generic types T, E
work in Java? Is it possible?
E oldItem;
E newItem = olditem.clone(); // does not work
Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields. Shallow copy is fast and also less expensive. Deep copy is slow and very expensive.
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
The answer is no. Cause there is no way to find out which class will replace your generic type E
during compile time, unless you Bind it to a type.
Java way of cloning is shallow, for deep cloning, we need to provide our own implementation
The work-around for it, is to create a contract like this
public interface DeepCloneable {
Object deepClone();
}
and an implementor should be having its own deep-clone logic
class YourDeepCloneClass implements DeepCloneable {
@Override
public Object deepClone() {
// logic to do deep-clone
return new YourDeepCloneClass();
}
}
and it can be called like below, where the generic type E
is a bounded type
class Test<E extends DeepCloneable> {
public void testDeepClone(E arg) {
E e = (E) arg.deepClone();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With