• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to Assign an object to another of the same kind?  RSS feed

 
Sergio Campos J.
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java doesn't mark a compilation error,
but it seems not to accept this assignment:

Object2 = Object1;

Provided that Object1 and Object2 are of the same kind with one array and one int variable inside them, and both declared as TestClass.
The code runs. but results shows the assignment above fails.

Is there a "formal way" of doing this assignment?
(I'm trying to avoid assigning item by item from inside objects)

Thanks in advance.

From Venezuela:
Wish you all a Merry Christmas
and A Happy New Year!!!
 
mike ryan
Ranch Hand
Posts: 210
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am beginner but i will give my thoughts about your question and see if i am correct, as i am sure others will correct me if i am wrong.

I don't think it is possible to make one object another as they are 2 completely different references of the same class.
I believe you could compare them but not make one become another.
 
Sergio Campos J.
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks mike!
Actually, assigning item by item is cheap here.
But in a more complex construction it could be quite expensive.
That's why I'm sure there should be a way of doing this.
 
mike ryan
Ranch Hand
Posts: 210
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sergio,

Like i said i am new so it is completely possible i am wrong(or even probable ;)....)
 
fred rosenberger
lowercase baba
Bartender
Posts: 12562
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what do you mean by "results shows the assignment above fails"? Can you show us your code?

I'm not sure, but you may be talking about what's called a "deep copy" vs. a "shallow copy". Try googling those terms and see if that helps.
 
Sergio Campos J.
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:[...] google "deep copy" [...] see if that helps.

It helped, Yes! Thank you!
TestClass Object2 = (TestClass) Object1.clone();

I think I was overwriting Object1 (shallow copy) which was supossed to stay unaltered
 
fred rosenberger
lowercase baba
Bartender
Posts: 12562
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glad i was able to point you in the right direction.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!