Thursday 18 August 2011

Java ArrayList copy constructor

The copy constructor of ArrayList in Java provides a shallow copy of the elements in the list. This is kind of expected, but I stilled wrote a test to verify this.

public class Test {
  public static void main(String[] args) {
    ArrayList<Point> list1 = new ArrayList<Point>();
    list1.add(new Point(1, 2));
    System.out.println("list1: " + list1);
    ArrayList<Point> list2 = new ArrayList<Point>(list1);
    list2.get(0).x = 3;
    list2.get(0).y = 4;
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
  }
}

Output:
list1: [java.awt.Point[x=1,y=2]]
list1: [java.awt.Point[x=3,y=4]]
list2: [java.awt.Point[x=3,y=4]]

Cloning an array of primitives, like int, is deep cloning. For example:
public class Test {
  public static void main(String args[]) {
    int[] a = {1, 2, 3, 4};
    int[] b = a.clone();
    b[0] = 5;
    System.out.println("a = " + Arrays.toString(a));
    System.out.println("b = " + Arrays.toString(b));
  }
}

The output is:
a = [1, 2, 3, 4]
b = [5, 2, 3, 4]

No comments :

Post a Comment