Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've implemented a copy constructor in Java 8 and use it like this:

User user = // some object
LOG.debug("{}", user);
this.userAccount = new User(user);
LOG.debug("{}", this.userAccount);

Output:

User@2799061
User@2799061

It's the same object! How can this be? Is this some kind of optimalization of which I'm unaware?

Also, my 'User' class is a JPA managed entity. Can this somehow interfere?

share|improve this question
1  
It cannot be the same instance of User, but the toString() method can give the same results and surely it gives. –  Dmitry Ginzburg May 26 at 13:22
    
The answer to the question in your title is no. Maybe you are not running the code you've shown, maybe the toString method has been overriden, maybe you are unlucky that the default toString method is printing the same thing for two different objects (you could print user == this.userAccount instead) etc... –  assylias May 26 at 13:22
add comment

1 Answer

up vote 8 down vote accepted

It's the same object!

No, it isn't. It just results in the same output when you use it with your LOG.debug method. If LOG.debug is using toString, that means it has the same string result from toString. This could be because of your implementation of toString, or it could be because the object has the same hash code, since the standard Object#toString outputs the class name, @, and then the hash code in hex. See Object#toString in the Javadoc for details, but basically:

The toStringmethod for classObjectreturns a string consisting of the name of the class of which the object is an instance, the at-sign character@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Re your title:

Can implementing Java copy constructor result in same instance?

No, not in Java.

share|improve this answer
1  
For some reason I've never connected the toString() hash and my own implementation of hashCode(). >< I'll accept your answer as soon as SO will let me. –  matsa May 26 at 13:27
    
@matsa: :-) I can totally see how that disconnect could happen. –  T.J. Crowder May 26 at 13:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.