Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sumit Bansal
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Shahnawaz Shakil
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Pie
Posts: 49451
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Sumit" please check your private messages about an important administrative matter.

CR
 
Arijit Daripa
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic