views:

202

answers:

4

clone method vs copy constructor in java. which one is correct solution. where to use each case?

+2  A: 

Clone is broken, so dont use it.

THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring

Prefer a method that copies the object

Foo copyFoo (Foo foo){
  Foo f = new Foo();
  //for all properties in FOo
  f.set(foo.get());
  return f;
}

Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx

Tom
Um, clone isn't broken. Why do you think it is? If it is because it doesn't work if you don't override it - well, that's its contract.
Bozho
@Bozho, read _Effective Java 2nd Edition_, Bloch explained it quite well. Doug Lea doesn't even use `clone()` anymore except to clone arrays (http://www.artima.com/intv/bloch13.html).
polygenelubricants
I don't really understand why cloning cannot be simpler. Is this a choice ? or there are really harsh problems behind that in the general case ?
LB
Not sure about that `copyFoo` code.
Tom Hawtin - tackline
f should be returned
LB
@LB, thanks, fixed.
Tom
@polygenelubricants `clone()` and `Cloneable` are wrong from design perspective. It's not that they don't work per se. And all shallow copies may behave randomly. That's why I suggested the deep copy mechanism.
Bozho
@Bozho: that's like saying that a square wheel is only wrong from design perspective only. You can install it on a car and the car will still move. "It's not that they don't work per se."
polygenelubricants
@polygenelubricants I'm not using `clone()` either, that's why I suggested beanutils. But my point is that `clone()` _can_ be used, though _"judiciously"_. In simple cases it works pretty well. So let's ammend the car metaphor - it's like saying that Russian cars work. Well, they do, but not quite well.
Bozho
+1  A: 

Have in mind that clone() doesn't work out of the box. You will have to implement Cloneable and override the clone() method making in public.

There are a few alternatives, which are preferable (since the clone() method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:

Bozho
+2  A: 

See also: How to properly override clone method?. Cloning is broken in Java, it's so hard to get it right, and even when it does it doesn't really offer much, so it's not really worth the hassle.

polygenelubricants