Java Collection Tutorial - Java ArrayList.clone()


ArrayList.clone() has the following syntax.

public Object clone()


In the following code shows how to use ArrayList.clone() method.

It shows that the clone() method is not doing deep clone.

//from  w  w w  .j ava  2  s . c  o  m

import java.util.ArrayList;

public class Main {
  public static void main(String args[]) {

    // create an empty array list
    ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>();

    // use add for new value
    arrlist1.add(new StringBuilder("from"));

    // using clone to affect the objects pointed to by the references.
    ArrayList arrlist2 = (ArrayList) arrlist1.clone();

    // appending the string
    StringBuilder strbuilder = arrlist1.get(0);


The code above generates the following result.