Why do we use the clone() method in Java?

Abhisek picture Abhisek · Apr 27, 2011 · Viewed 35.8k times · Source

Why do we use the clone() method in Java? (Please give the answer in respect of memory constraint.) Will that reduce memory usage? If yes, then how? Will that reduce the effect of memory leak?

Answer

Andreas Dolk picture Andreas Dolk · Apr 27, 2011

Apart from do not use clone, implement a copy constructor, you asked about memory constraints.

The idea of cloning is to create an exact duplicate of the cloned object. So in worst case, you use twice the amount of memory afterwards. Practically - a bit less, because Strings are often interned and will (usually) not be cloned. Even though it's up to the implementor of the clone method/copy constructor.

Here's a short example of a class with a copy constructor:

public class Sheep {
  private String name;
  private Fur fur;
  private Eye[2] eyes;
  //...

  // the copy constructor
  public Sheep(Sheep sheep) {
    // String already has a copy constructor ;)
    this.name = new String(sheep.name);

    // assuming Fur and Eye have copy constructors, necessary for proper cloning
    this.fur = new Fur(sheep.fur); 
    this.eyes = new Eye[2];
    for (int i = 0; i < 2; i++) 
       eyes[i] = new Eye(sheep.eyes[i]);
  }
}

Usage:

Sheep dolly = getDolly();  // some magic to get a sheep
Sheep dollyClone = new Sheep(dolly);