Monday, October 15, 2007

Use of clone method - cloning objects

The reason for making a local copy of an object is if you’re going to modify that object and you don’t want to modify the caller’s object. If you decide that you want to make a local copy, you simply use the clone() method to perform the operation. For example, the standard library class ArrayList overrides clone(), so we can call clone() for ArrayList:
import java.util.*;

class Int {

private int i;

public Int(int ii) { i = ii; }

public void increment() { i++; }

public String toString() {
return Integer.toString(i);
}
}

public class DemoCloning {

public static void main(String[] args) {
ArrayList al = new ArrayList();

for(int i = 0; i < 10; i++ )
al.add(new Int(i));

System.out.println("al: " + al);

ArrayList al1 = (ArrayList)al.clone();

// Increment all al1's elements:
for(Iterator e = al1.iterator(); e.hasNext(); )
((Int)e.next()).increment();

// See if it changed al's elements:
System.out.println("al: " + al);
}
}

The clone() method produces an Object, which must then be recast to the proper type. This example shows how ArrayList’s clone() method does not automatically try to clone each of the objects that the ArrayList contains—the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it’s copying only the “surface” portion of an object. The actual object consists of this “surface,” plus all the objects that the references are pointing to, plus all the objects those objects are pointing to, etc. This is often referred to as the “web of objects.” Copying the entire mess is called a deep copy. You can see the effect of the shallow copy in the output, where the actions performed on al1 affect al:

al: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
al: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

No comments: