Forums Register Login

Java object copy(Without Clone)

+Pie Number of slices to send: Send
Hi All,
Why java copies Address instead of values when we assign like this
ArrayList test=new ArrayList();
ArrayList test1=new ArrayList();
test=test1;//Both share the same memory .

As far as i Know this can be avoided by using the Clone Method. I can go for Clone supported by object if the using object doesn't contain any object itself i.e it contains only primitive data type or else we need to explicitly implement cloneable interface .Why java doesn't support the copy by value method as it supports equals (A method to override == ).

Thanks
Maruthi
[ December 22, 2005: Message edited by: Michael Ernest ]
+Pie Number of slices to send: Send
I think you should go back a little and review the lessons about references. I java you always have the reference to an object and never the value (OK, you have the value of the reference). What you do is assign the value of one reference to another value. About equals(Object) and == - they are quite different things - two objects may be equal, but not the same since == compares reference equality.
+Pie Number of slices to send: Send
Hi
I know the difference.Thats why I am asking, why they didn't support the copy operation when they are supporting the 'equal' method instead of '=='(due to referrence).
+Pie Number of slices to send: Send
Hi Maruthi,

Your just assiging the test1 reference to test. after the assignment line , there will be only one Arraylist. there other create by test will gone to GC.

~With SMile
VK
Are you okay? You look a little big. Maybe this tiny ad will help:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2627 times.
Similar Threads
Question regarding Cloneable interface and Subclasses
Benefit Of Using Key as Object In HashMap
cloning
Creating an object vs copying it
ArrayList clone question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 22:34:54.