Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 310
Michael Dorner Avatar asked May 08 '13 09:05

Michael Dorner


People also ask

What is the deep copy in Java?

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.

Is Java clone a deep copy?

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.

Is Java deep copy or shallow copy?

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.

How do you pass a generic object in Java?

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);


1 Answers

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();
    }
}
like image 135
sanbhat Avatar answered Sep 24 '22 03:09

sanbhat