• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java object copy(Without Clone)  RSS feed

 
Maruthi Chokkanathan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Khan Malamir
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maruthi Chokkanathan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Karthikeyan Varadarajan
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!