Search code examples
javalistclone

Make a deep copy with clone


I am having a list of company objects. I am trying to clone this list with:

public static List<Company> cloneList(List<Company> list) {
    List<Company> clone = new ArrayList<Company>(list.size());
    for(Company item: list) clone.add(item.clone());
    return clone;
}

However my compiler says:

Multiple markers at this line
    - The method add(Company) in the type List<Company> is not applicable for the arguments 
     (Object)

Why is this not possible to make a deep copy with clone()?


Solution

  • The clone() method is defined on the root class Object (see here). It returns an Object, therefore, if you haven't changed its return type to the concrete class while overriding, you have to cast it to the proper type, e.g. :

    clone.add((Company) item.clone());
    

    or define clone() with a covariant return type in your class as:

    public class Company implements Cloneable {
       // stuff ...
    
       public Company clone() throws CloneNotSupportedException { /* do clone */ }
    }    
    

    Note that you have to override the clone method as it is defined with visibility protected.

    By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method. [source]

    Also see this question for other options.