Search code examples
javagenericsclonegeneric-programming

Deep Copy of a Generic Type in Java


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

Solution

  • 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();
        }
    }