Java variable aliasing workaround - java

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?

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.

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.

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.

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

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.

Related

Deep Clone Non Seriazable object in java

I need to deep clone a object which has some non-serialization objects as members in Java.
Can you provide some reference what can i use for this ?
Note:
Please provide reference to some standard library of java. I don't want to use any unapproved/private package or library.
Or some code pointers how can i clone the object ?
In the absence of standardisation of values in Java, I strongly suggest avoiding any dodgy reflection/code generation scheme.
If you can, changing to immutable types removes the need to copy.
Other than that, just write the code neatly. If there are a lot of collections, writing map methods will help to avoid the palaver of Streams (and be faster).

Strong Reference class

Why is there no java.lang.ref.StrongReference class in jdk1.7? (see JDK-6392701)
I am trying to implement a behavior that needs to be able to store Objects in different reference strengths. So my first thought was to use a field of type Reference<T> and asign a Referece with of desired strength. But there is no class for Strong references and extending Reference manually seems like the completely wrong direction.
The alternative would be to have two field, one that is a Reference and the other that is of the desired type and have only one set but a Reference that strongly stores the values would make the code much cleaner.
...and extending Reference manually seems like the completely wrong direction.
It's worse than that. According to the API:
Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.
If you want to be able to store multiple different kinds of references, including strong, in the same structure, the best bet is probably to make your own reference interface and make two implementations: one wrapping a Reference<T> and one wrapping a normal object.

Deep Copy an Object

Is it possible to deep copy an Object out of the box? i.e. any other way than coding a clone function manually.
Cloning does not necessarily perform a deep copy. In fact, the default implementation of Object.clone() creates a shallow copy.
If the object's closure consists of objects that implement Serializable or Externalizable, you can use ObjectOutputStream and ObjectInputStream to create a deep copy ... but it is expensive.
The cloning library is another option, but my initial reading of the code is that it relies on the class of every object in the graph providing a no-argument constructor. Then it will then patch the resulting object to have a copy of the original object's state. This process might have undesirable side-effects, depending on what the no-args constructor actually does.
In short, I don't think there is a universal solution.
I suggest to use java.lang.reflect.
java.lang.Class expose all fields and allows reading public fields and calling public methods.
Only the private field without accessors can't be cloned.
I briefly looked at the cloning library code. It does what Serialization does that is get the graph of the object internal and instead of writing to file, it writes to a memory location = which is the clone of the object. So although its faster than Serialization, its certainly doing the same thing.

Use instance variable in conjunction with objects

Greetings fellow programmers!
So I've been learning java for 2 months and its been a really awesome experience and journey. There's a confusing thing in java I still don't know why I can do it. The idea is using using instance variable in conjunction with objects.
How come I can specific the objectname.instance variable associated with the object? What's this process called?
It's called dereferencing, the same as calling a method via objectname.method(). Note that strictly speaking, it's not the object's name, but the name of the reference (there can be many references with different names refering to the same object).
Note also, that it's considered better to encapsulate instance variables by making them private and providing set/get methods if necessary.
That'd be dereferencing, I believe. It's not as explicit in Java as in languages that confront you with concepts like pointers or memory offsets.

Why people are so afraid of using clone() (on collection and JDK classes)?

A number of times I've argued that using clone() isn't such a bad practice. Yes, I know the arguments. Bloch said it's bad. He indeed did, but he said that implementing clone() is bad. Using clone on the other hand, especially if it is implemented correctly by a trusted library, such as the JDK, is OK.
Just yesterday I had a discussion about an answer of mine that merely suggests that using clone() for ArrayList is OK (and got no upvotes for that reason, I guess).
If we look at the #author of ArrayList, we can see a familiar name - Josh Bloch. So clone() on ArrayList (and other collections) is perfectly fine (just look at their implementations).
Same goes for Calendar and perhaps most of the java.lang and java.util classes.
So, give me a reason why not to use clone() with JDK classes?
So, give me a reason why not to use clone() with JDK classes?
Given an ArrayList reference, you would need a getClass check to check that it is not a subclass of the JDK class. And then what? Potential subclasses cannot be trusted. Presumably a subclass would have different behaviour in some way.
It requires that the reference is more specific than List. Some people don't mind that, but the majority opinion is that that is a bad idea.
You'll have to deal with a cast, an unsafe cast at that.
From my experience, the problem of clone() arises on derived classes.
Say, ArrayList implements clone(), which returns an object of ArrayList.
Assume ArrayList has an derived class, namely, MyArrayList. It will be a disaster if MyArrayList does not override the clone() method. (By default it inherits the code from ArrayList).
The user of MyArrayList may expect clone() to return an object of MyArrayList; however, this is not true.
This is annoying: if a base class implements clone(), its derived class has to override the clone() all the way.
I will answer with a quote from the man himself (Josh Bloch on Design - Copy Constructor versus Cloning):
There are very few things for which I use Cloneable anymore. I often provide a public clone method on concrete classes because people expect it.
It can't be any more explicit than this: clone() on his Collection Framework classes are provided because people expect it. If people stop expecting it, he would've gladly thrown it away. One way to get people to stop expecting it is to educate people to stop using it, and not to advocate its use.
Of course, Bloch himself also said (not exact quote but close) "API is like sex: make one mistake and you support it for life". Any public clone() can probably never be taken back. Nevertheless, that's not a good enough reason to use it.
In order not to encourage other, less experienced, developers to implement Clone() themselves. I've worked with many developers whose coding styles are largely copied from (sometimes awful) code that they've worked with.
It does not enforce whether the implementer will do a deep or shallow copy.
Using clone can be risky very risky if you don't check the implementation of this clone method... as you can suppose a clone impl can act in different ways... shallow or deep clone... and some developpers may not always check what kind of clone they will retrieve...
In a big application, big team, it's also risky because when cloning is used, if you modify the clone implementation you may modify the application behaviour and create new bugs... and have to check everywhere the clone was called (but it can be the same for other object methods like equals, toString...
When modifying the clone of a small subclass A (from Deep to Shallow clone for exemple), if an instance of B has a reference to A and a deep clone impl, then since the objects referenced in A are not shallow cloned, the B clone won't be a deep clone anymore (and it's the same for any class referencing a B instance...).
It's not easy to deal with the deepness of your clone methods.
Also when you have an interface (extending Clonable) and many (many!) implementations, sometimes you will check some impl and see that clones are deep, and call a clone on the inteface but you can't be sure at runtime all impl really have deep clone and can introduce bugs...
Think it could be better to impl for each method a shallowClone and a deepClone method, and on very specific needs implement customised methods (for exemple you want a clone and limit the depth of this clone to 2, make a custom impl for that in all classes concerned).
Don't think it's a big matter to use a clone method on a JDK class since it's not going to be changed by another developper, or at least not often. But you'd better not call clone on JDK classes if you don't know the class implementation at compile time. I mean calling the clone on an ArrayList is not a matter but calling it on a Collection could be dangerous since another Collection implementation could be introduced by another developper (he can even extends a Collection impl) and nothing tells you that the clone of this impl will work like you expect it to do...
If the types in your collection are mutable, you have to worry about whether just the collection, itself, will be cloned, or whether the elements will also be cloned... hence implementing your own function, where you know whether the elements or just the container will be cloned will make things much clearer.

Categories