views:

328

answers:

4

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?

+1  A: 

java.lang.Cloneable is what you are looking for.

Journeyman Programmer
+5  A: 

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.

marcog
Just as useful as mihi's answer, but I liked all the useful links on this one. The links give me ways to find out more information if needed. Anyways, I implemented some sort of copy constructor.
Cory Walker
clone is very dangerous. It does a "bitwise" copy, which is almost never what you want. Whilst you can, to some extent, insert correcting code you are likely to quietly mess it up from time to time. It also doesn't play well with inheritance.
Tom Hawtin - tackline
+3  A: 

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.

mihi
I suspect you can subclass FileInputStream and implement Cloneable, the clone will work just fine. Perhaps a bit strange, but I think it'll actually give you two stream object onto the same FileDescriptor (not checked the source recently).
Tom Hawtin - tackline
+1  A: 

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.

Peter Lawrey