Reminders sa mga rehistradong myembro:

•ang lengwahe na gagamitin ay pawang english at tagalog lamang

•Bawal po dito ang pakikipag away

•Bawal ang mga shorcut na mga words
Example: txt, Pwd, at iba pa

•Bawal mababastos at masasakit na salita o anu mang makakasakit
ng damdamin ng isang myembro ng forum na ito

•use the "like" button if the post of the following user you think are usefull

JAVA - ArrayList Cloning Technique

Go down

Admin Post JAVA - ArrayList Cloning Technique

Post by princeterror on Sat Sep 22, 2012 4:36 am

What is cloning?

Cloning is the ability to copy one object to another object.

What is the purpose of cloning?

Once object already copied to another object, the new object doesn't affect the attributes or values of the original object.

Can we clone ArrayList?

Yes. There are two types of cloning we can achieve in ArrayList. Shallow Clone and Deep Clone.

Shallow clone is the ability to copy its container while Deep clone is the ability to clone to its elements which is composed of another objects.

Shallow Clone:

ArrayList aListOriginal = new ArrayList();

ArrayList aListClone = new ArrayList();
aListClone = aListOriginal.clone(); //Replica of aListOriginal.

aListClone.set(1, "D"); // Now, first element of the cloned ArrayList will become "D", but it won't affect the first element of the aListOriginal which is "A".

Deep Clone:

ArrayList aListParent= new ArrayList();
ArrayList aListChild = new ArrayList();

aListParent.add(aListChild.clone()); // Shallow Clone.

ArrayList aListClone = new ArrayList();
aListClone = (ArrayList)((ArrayList)aListParent.get(1)).clone();

aListClone.set(1, "D");

Based on the above example, aListClone element is came from aListChild. aListParent is the container of aListChild.

Now, the first element of aListClone already changed, but, the first element of aListChild remain unchanged!
Universal Moderator
Universal Moderator

Posts : 272
Credits : 11465
Fame : 81
Join date : 2012-06-07
Age : 27

Back to top Go down

Back to top

Permissions in this forum:
You cannot reply to topics in this forum