149

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

3
  • 6
  • 3
    Avoid clone at all costs and go for your own copy solution.
    – dimitarvp
    Mar 12, 2010 at 10:51
  • Copy constructors are better than Object.clone() because they Don’t force us to implement any interface or throw any exception but we can surely do it if it is required, Don’t require any casts, Don’t require us to depend on an unknown object creation mechanism, Don’t require parent class to follow any contract or implement anything, Allow us modify final fields, Allow us to have complete control over object creation, we can write our initialization logic in it. Read more programmingmitra.blogspot.in/2017/01/… Jan 11, 2017 at 17:18

6 Answers 6

120

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

11
  • 25
    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
    Mar 11, 2010 at 19:23
  • 29
    @Bozho, read Effective Java 2nd Edition, Bloch explained it quite well. Doug Lea doesn't even use clone() anymore except to clone arrays (artima.com/intv/bloch13.html). Mar 11, 2010 at 19:45
  • 2
    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 ?
    – LB40
    Mar 11, 2010 at 19:52
  • 9
    @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
    Mar 11, 2010 at 20:35
  • 8
    I freely admit that I haven't (yet) read Effective Java but I will say that Cloneable has the advantage of being an interface. That is to say that you can limit the parameters of generic classes and functions to only accept classes that implement Cloneable, then simply call clone(). Without it, I don't believe there is a (good) way to enforce that and you would likely resort to reflection to discover a class's copy constructor. That also makes the assumption that if Foo has a constructor that accepts a Foo, that is in fact a copy constructor. At least you know what clone() should return.
    – spaaarky21
    Sep 25, 2014 at 15:04
58

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:

4
  • 1
    How does that deep cloning library work on any object? I smell code that is probably riddled with reflection
    – Cruncher
    Dec 9, 2013 at 13:58
  • 2
    yes, a lot of reflection :)
    – Bozho
    Dec 10, 2013 at 7:50
  • which of these does not copy references and copy by values? BeanUtils.cloneBean(bean) is copying references, but im using an android version (android-java-air-bridge.jar) not original apache version. Nov 9, 2016 at 18:20
  • i have tried java deep cloning library and works great!! it does not copy references :D, copy values Nov 9, 2016 at 18:36
34

clone() was designed with several mistakes (see this question), so it's best to avoid it.

From Effective Java 2nd Edition, Item 11: Override clone judiciously

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

This book also describes the many advantages copy constructors have over Cloneable/clone.

  • They don't rely on a risk-prone extralinguistic object creation mechanism
  • They don't demand unenforceable adherence to thinly documented conventions
  • They don't conflict with the proper use of final fields
  • They don't throw unnecessary checked exceptions
  • They don't require casts.

All standard collections have copy constructors. Use them.

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
1
  • 5
    You are copying original as an ArrayList when it may have been another type of list (e.g. LinkedList). This is exactly why clone is better than a copy constructor.
    – Steve Kuo
    Nov 4, 2015 at 16:54
19

Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:

// Need to clone person, which is type Person
Person clone = new Person(person);

This doesn't work if person could be a subclass of Person (or if Person is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).

Person clone = (Person)person.clone();

or

Person clone = (Person)SomeCloneUtil.clone(person); // See Bozho's answer

Now person can be any type of Person assuming that clone is properly implemented.

2
  • It's unfortunate that someone once suggested that a proper implementation of clone should involve new rather than super.clone(), since the proper behavior for clone is to call super.clone() if that method itself calls super.clone() (or is the built-in memberwise clone for object); if super.clone() ends up calling new, the only not-totally-broken behavior for clone() is to call new itself, but then every child class must override clone() to do likewise whether or not the child class would otherwise need to override clone().
    – supercat
    Jun 26, 2012 at 15:02
  • The "deep vs shallow" question doesn't seem ambiguous to me in most cases. A SomeCollection<T> exists to hold the identities of things of type T, and calling clone() on one should yield a new instance of the same type which is detached from the original but holds references to the same T's. Nothing that can be done to the original or the clone should affect the identities of the objects stored in the other. I really don't understand what the confusion is.
    – supercat
    Jun 26, 2012 at 15:06
3

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.

1
  • It's much easier to get right when you have a final class that inherits from java.lang.Object. It's tricky when the class contains mutable data structures (and thus requiring a deepcopy), but the same challenge would also present itself in a copy constructor.
    – IceArdor
    Feb 7, 2018 at 0:58
2

Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().

Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).

Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).

4
  • There is some hope for this sort of thing, at least for value objects that you make in your project: projectlombok.org/features/experimental/Wither.html
    – Roboprog
    Nov 3, 2016 at 1:18
  • 1
    If copying was easy, it already would have been part of Java. But it isn't. Do you want a shallow copy, a deep copy, or somewhere in between? Do you have different behaviors for different classes depending on what you're copying and what you're casting to? What happens with Generics? What happens when what you're copying is a parameter for a Generic? This might be a bit easier to reason about without inheritance and without mutability, but those are baked into the heart of Java (the language). Maybe a language like Scala that makes guarantees about mutability will make cloneability easier.
    – IceArdor
    Feb 7, 2018 at 1:01
  • @IceArdor - I want a shallow copy, with type inference about the result based on the source, and the same implementing class used internally. At least, if the source implementation has a default constructor, I guess.
    – Roboprog
    Apr 12, 2018 at 19:02
  • @Roboprog Are you sure that shallow copy didn't work when you wrote your comment years ago? Shallow copies almost never make sense to me. newMap = new HashMap<>(oldMap) works when I really just need shallow copy. Apr 27, 2018 at 11:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.