Deep copy of generic type in Java

How do deep copies (clones) of common T, E types in Java work? Is it possible?

 E oldItem; E newItem = olditem.clone(); // does not work 
+4
source share
1 answer

The answer is no. Because there is no way to know which class will replace your generic type E at compile time if you don't bind it to the type .

The Java cloning method is shallow, for deep cloning we need to provide our own implementation

The workaround for him is to create such a contract

 public interface DeepCloneable { Object deepClone(); } 

and the developer must have his own deep clone of logic

 class YourDeepCloneClass implements DeepCloneable { @Override public Object deepClone() { // logic to do deep-clone return new YourDeepCloneClass(); } } 

and it can be called as shown below, where the generic type E is a restricted type

 class Test<E extends DeepCloneable> { public void testDeepClone(E arg) { E e = (E) arg.deepClone(); } } 
+2
source

Source: https://habr.com/ru/post/1479695/


All Articles