Tuesday, 15 August 2017

java - shallow copy - new instance Or assignment



Shallow copy means a "copy" of an object with same values of their attributes whether primitive or reference values.




While performing shallow copy is it necessary to "create a new instance" ? as:



public class A {
int aValue;
B bObj;

...

public A createShallow(A a1Obj) {

A aObj = new A();
aObj.aValue = a1Obj.aValue;
aObj.bObj = a1Obj.bObj;

return aObj;
}
}


Or copy by assignment is also considered as shallow copy:




B b = new B(10);
A a = new A(1, b);

A a1 = a;


This article at wikipedia defines shallow copy as reference variables sharing same memory block. So according to this copy by assignment will also be a shallow copy.



But is not it a variables pointing to same object instead of "copy" of an Object ?



Answer




While performing shallow copy is it necessary to "create a new
instance" ?




Yes, you must create an instance to create a copy (either shallow or deep) of your object. Just doing the assignment of reference just creates a copy of reference which points to the same instance.



You have used a non-static method that is creating a copy. But generally I prefer two ways: -




Either use a copy-constructor: -



public A(A obj) {
copy.aValue = obj.aValue;
}


And use it like: -



A first = new A();

A copy = new A(first);


Or, use a public static method which takes an instance and returns a copy of that.



public static A createCopy(A obj) {
A copy = new A();
copy.aValue = obj.aValue;
return copy;
}


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...