Reputation: 4987
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?
Upvotes: 5
Views: 7254
Reputation: 127
Another option is to design your class to create immutable objects:
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
This avoids the need for cloning or a copy-constructor because the object cannot be changed once it is created. So multiple variables can point to the same object, but none of them can change the state of the object.
Upvotes: 2
Reputation: 533660
You cannot have an implicit reference to a reference in Java so you cannot alias a variable.
Perhaps if you explain what you are trying to achieve, we can help do that without "aliases"
Edit: You really need to explain what you mean by aliasing an int value. An int value is anonymous at runtime so aliasing it doesn't make any sense.
Upvotes: 1
Reputation: 6735
It depends on the "content". For example, you cannot just copy a FileInputStream and then assume that both will continue loading from the same file.
Basically, there are two ways: If the class supports "Cloneable" interface, you can clone it by calling clone(). If not, it often has a copy constructor, that copies in data from another object.
Usually, you will end up with a shallow copy (i. e. all fields of the class are copied, but they point to the same object).
On the other hand, a lot of objects are designed to be immutable (like the String class), and there is no need to copy such an object as it cannot be changed anyway.
Upvotes: 4
Reputation: 138397
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.
Upvotes: 11