Total members 11890 |It is currently Fri Apr 19, 2024 5:05 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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.



_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

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



Topic Tags

Java OOP
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com