Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable aliasing workaround

I've recently moved to Java, but I've had some problems with variable aliasing. I've searched everywhere, but I can't seem to find the proper way to copy the contents of one object to another object without just referencing to the same object. Does anyone have any suggestions?

Edit: What if it is an int that I am having aliasing problems with? Should I be avoiding situations like this in the first place? If so, how?

like image 217
Cory Walker Avatar asked Apr 25 '09 19:04

Cory Walker


1 Answers

If your class implements the Clonable interface, then you can use the Object.clone() method to create a hard copy. The Wikipedia entry has some good details.

An alternative is to use copy constructors, which according to this page are safer.

like image 135
moinudin Avatar answered Sep 26 '22 19:09

moinudin