aspose file tools *
The moose likes Java in General and the fly likes how object.clone() is different then direct reference assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how object.clone() is different then direct reference assignment" Watch "how object.clone() is different then direct reference assignment" New topic
Author

how object.clone() is different then direct reference assignment

Sumit Bansal
Greenhorn

Joined: Feb 27, 2007
Posts: 19
HashMap h1 = new HashMap();
h1.put("one", "one");
h1.put("two", "two");
h1.put("three", "three");
h1.put("four", "four");
h1.put("five", "five");
HashMap h2 = null;
1)//h2 = h1; // Assign reference directly
2)h2 = (HashMap)h1.clone(); // make a clone of the object
h1 = null;

If you try option (1) or (2), both gives the same result, i have tried it. then what is the difference between these two ways [except clone() instantiate a new object with same values]?
Also which one is more efficient and right to use?


Sumit Bansal<br /> <br />SCJP 5.0
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57


Run above code you will find the difference. The difference is that the change in the object refered by h1 is reflected by h2 because it is refering to same object. But the same is not reflected by h3 because it is refering to a different object. Cloning simply means that the values in the object are same but anyway its a different object.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40079
    
  28
"Sumit" please check your private messages about an important administrative matter.

CR
Arijit Daripa
Ranch Hand

Joined: Aug 09, 2008
Posts: 142
Originally posted by Sumit Bansal:
HashMap h1 = new HashMap();
h1.put("one", "one");
h1.put("two", "two");
h1.put("three", "three");
h1.put("four", "four");
h1.put("five", "five");
HashMap h2 = null;
1)//h2 = h1; // Assign reference directly
2)h2 = (HashMap)h1.clone(); // make a clone of the object
h1 = null;

If you try option (1) or (2), both gives the same result, i have tried it. then what is the difference between these two ways [except clone() instantiate a new object with same values]?
Also which one is more efficient and right to use?


When more than one reference are referring same object (not an immutable one), change made through one reference is reflected through any other.

If my father destroys his house, I will also have my house destroyed; because we are under same roof.


SCJP 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how object.clone() is different then direct reference assignment