Workaround for Java Aliases

I recently switched to Java, but I had some problems with a variable alias. I searched everywhere, but I can’t find a suitable way to copy the contents of one object to another object without referring only to the same object. Anyone have any suggestions?

Edit: what if this is an int that I'm facing smoothing issues? Should I avoid situations like this in the first place? If so, how?

+4
source share
5 answers

If your class implements the Clonable interface, you can use Object.clone () to create a hard copy. There are some good details on the Wikipedia entry.

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

+10
source

It depends on the "content". For example, you cannot just copy a FileInputStream, and then assume that both will continue to download from the same file.

Basically, there are two ways: if the class supports the Cloneable interface, you can clone it by calling clone (). If not, it often has a copy constructor that copies data from another object.

Usually you end up with a shallow copy (i.e. all the fields of the class are copied, but they point to the same object).

On the other hand, many objects are designed as immutable (for example, the String class), and there is no need to copy such an object, since it cannot be modified in any way.

+4
source

Another option is to create your own class to create immutable objects:
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html

This avoids the need for cloning or copy constructor, since the object cannot be modified after its creation. Thus, several variables can point to the same object, but none of them can change the state of the object.

+2
source

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

+1
source

You cannot have an implicit link to a link in Java, so you cannot list a variable.

Perhaps, if you explain what you are trying to achieve, we can help to do it without "aliases"

Edit: You really need to explain what you mean by an alias. The int value is anonymous at runtime, so anti-aliasing does not make any sense.

+1
source

All Articles