Reputation: 4870
I'm stuck at this since a very long time.
tell me if the following code makes a clone or not?
class A
{
int i;
int j;
String str;
A()
{
i=10;
j=30;
str="Hello";
}
A(A a)
{
this.i=a.i;
this.j=a.j;
this.str=a.str;
}
}
class B
{
public static void main(String args[])
{
A a = new A();
A a1 = new A(a);
/* I want to make clone like this. */
}
}
when I run this code and when I print hashcode of a and a1, they are different. But some of my friends say that this is not the correct way to make a clone. You have to implement the Cloneable interface, is that really necessary? In my opinion, it can be a good approach if I want to make a deep copy even in case of derived reference variable. Thank you.
Upvotes: 1
Views: 249
Reputation: 535
You need to implement the Clonable interface in order to clone an object. What you have implemented is called a copy constructor. Copy constructors are preferable to implementing Clonable.
The reason your copied object has a different hashcode/equals from the object it is copied from is because you haven't overridden the hashcode or equals functions in your A class so it's checking for identity rather than just equality (the exact same object, not an object with the same values). By overriding hashcode/equals you can make your class compare the values of it's properties instead.
Upvotes: 2