Java ArrayList.clone()

Syntax

ArrayList.clone() has the following syntax.

public Object clone()

Example

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

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


/* w  w  w  .j  a  v  a  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 java2s.com"));

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

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

    System.out.println(arrlist1);
    
    System.out.println(arrlist2);
  }
}

The code above generates the following result.