Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question on object cloning.

 
Vanchi Nathan
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello everyone,

i have tried the following code:
The question is the why is the line
(firstObj == secondObj)
not returning a true value?

Thanks in advance.
 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
API for clone() method of java.lang.Object class states:


Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x will be true, and that the expression:
x.clone().getClass() == x.getClass()will be true, but these are not absolute requirements.

While it is typically the case that:
x.clone().equals(x)will be true, this is not an absolute requirement.


Further more, the API states (and this point is vital):

Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.


Regards,
Saket
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

because it is not the same object but a clone...
remember: == checks if the reference points to the same object in memory, equals() checks if the objects are having the same state.

if firstObj == secondObj would be true, then the clone operation would actualy just return a reference to itself... which is not the intent. clone() should return a new object with the same state as the object you called clone() on.

do i make sense ?

pascal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic