Switch to full style
Java Technology Tutorials Written By Members.
Post a reply

when to use clone in java

Mon Jul 23, 2012 4:53 pm

In java we use references to link for objects places in memory, when using assignment between two references you only copying the memory address and not cloning the object in memory, a solution to this is overriding a function clone in your class. Clone function exists in the root class Object and you will need to override it in your own class and set the details of the cloning process. Clone function is defined as protected and you will need to override this function with public access provider. There are a standard library classes has clone function overridden for example “ArrayList” class , as you may see in the following code snippet :

Code:

import java
.util.ArrayList;
import java.util.Iterator;

 
public class Test 
{

    public static void main(String[] args) {
        ArrayList firstArray = new ArrayList();
        int size = 10;
        for (int i = 0; i < size; i++) {
            firstArray.add(new SumPool(i));
        }

        ArrayList secondArray = (ArrayList) firstArray.clone();

   

        for 
(int i = 0; i < size; i++) {
            ((SumPool) secondArray.get(i)).add(4);
        }

        for (int i = 0; i < size; i++) {
            // Notice that we printing the first array.
            System.out.println(((SumPool) firstArray.get(i)));
        }

    }
}

class SumPool {

    private float sum;

    public SumPool(float x) {
        sum = x;
    }

    public void add(float x) {
        sum += x;
    }

    public String toString() {
        return "current sum=" + sum;
    }

 
} 


The output of this snippet is :
Code:

current sum
=4.0
current sum
=5.0
current sum
=6.0
current sum
=7.0
current sum
=8.0
current sum
=9.0
current sum
=10.0
current sum
=11.0
current sum
=12.0
current sum
=13.0


Is that expected? This example showed that clone function of ArrayList classes doesn’t automatically clone each object inside the ArrayList objects; this copy is called Shallow copy because it is copying only the containers objects and not the classes inside it, A solution to this is to clone the array list elements too :
Code:


import java
.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {

    public static void main(String[] args) {
        
        ArrayList firstArray 
= new ArrayList();
        int size = 10;
        for (int i = 0; i < size; i++) {
            firstArray.add(new SumPool(i));
        }

        ArrayList secondArray = (ArrayList) firstArray.clone();
         for (int i = 0; i < size; i++) {
            try {
                secondArray.set(i, ((SumPool) firstArray.get(i)).clone());
            } catch (CloneNotSupportedException ex) {
                  Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
           }
          }


        for (int i = 0; i < size; i++) {
            ((SumPool) secondArray.get(i)).add(4);
        }

        for (int i = 0; i < size; i++) {
            // Notice that we printing the first array.
            System.out.println(((SumPool) firstArray.get(i)));
        }

    }
}

class SumPool implements Cloneable {

    private float sum;

    public SumPool(float x) {
        sum = x;
    }

    public void add(float x) {
        sum += x;
    }

    public String toString() {
        return "current sum=" + sum;
    }

    @Override
    public Object clone
() throws CloneNotSupportedException {
        return new SumPool(sum);
    }
}

 




Remember to override the Clone function as public as the Object class clone function is protected, there are some cases when u have an object that has a clone function but this object includes other objects as members that you are not sure about that are it clone-able or not, In such case you may go for “Serialization” which is usually used to transfer objects throw network or to XML file, the receiver will be able to reconstruct an object from the data sent, but also in such case the class should be serializable.



Post a reply
  Related Posts  to : when to use clone in java
 A clone instance of class in php     -  
 clone arrayList elements     -  
 2d game in java-Monster-Java 2D Game Graphics and Animation     -  
 what is java     -  
 Java course     -  
 What is Java API?!!!     -  
 java or .net     -  
 need help in java     -  
 Using FTP in java     -  
 Java applet     -  

Topic Tags

Java OOP