how-to

Classes

How to make shallow and deep copy of object

What is difference between shallow and deep copy of the object ?

VARIANT - SHALLOW COPY

This sample show sample shallow copy:

/* -- create object */

int[] a = new int[3];

a[0] = 100;
a[1] = 200;
a[2] = 300;

/* -- make shallow copy = make reference to same object in heap */

int[] b = a;

/* -- check, if the objects */

if ( a.equals( b ) )
  System.out.println( "Object are same." );
else
  System.out.println( "Object are not same." );

/* -- change in "b" object perform change in "a" object too */

b[1] = 10000;

System.out.println( Arrays.toString( a ) );
System.out.println( Arrays.toString( b ) );

How you can see, objects are same and change in "b" = change in "a":

Object are same.
[100, 10000, 300]
[100, 10000, 300]

VARIANT - DEEP COPY

This sample show sample deep copy:

/* -- create object */

int[] a = new int[3];

a[0] = 100;
a[1] = 200;
a[2] = 300;

/* -- make deep copy = copy object to another */

int[] b = a.clone();

/* -- check, if the objects */

if ( a.equals( b ) )
  System.out.println( "Object are same." );
else
  System.out.println( "Object are not same." );

/* -- change in "b" object perform change in "a" object too */

b[1] = 10000;

System.out.println( Arrays.toString( a ) );
System.out.println( Arrays.toString( b ) );

This variant shows copy of the object to another quite independent object. Change in "b" doesn`t affect "a":

Object are not same.
[100, 200, 300]
[100, 10000, 300]