Sometimes i want to “replace” an object with another object of the same class.
Usually i do this in the following way.
The object’s class with a constructor:
public class Type {
private int field;
private double anotherField;
public Type(Type anotherTypeInstance) {
this.field = anotherTypeInstance.getField();
this.anotherField=anotherTypeInstance.getAnotherField();
}
}
So whenever i want to replace the object I simply do this
Type oldInstance = new Type(newInstance)
Sometimes it is easy and convenient to do, while others not.
Is there an alternative?
EDIT:
I need this kind of “replacement” in optimization algorithms.
Where i have to replace the current Solution (object) whith another Solution that has a smaller cost
You can implement
Cloneableinterface and theclone()method like thisIf you do use
clone()for more complex classes, you need to make sure that all mutable objects referred to by fields of the class are recursively cloned as well, i.e. that you make a deep copy instead of a shallow copy. Accidental state sharing that can occur as a result of shallow copy can lead to problems which are hard to debug.The use of
clone()has a number of problems. It circumvents constructors which are normally a place where class’s initial invariants are enforced. It is very error prone for classes containing more than just primitive types. Also, the use ofclone()is incompatible with non-primitive final fields, since you cannot fix them after cloning an object in case they require modification to ensure deep copying.Consider for example this class:
Copy constructors like the one posted in the question are a much better approach.