Alexander
Alexander

Reputation: 20224

Cannot find symbol clone() in interface Cloneable

I am trying to clone a list of Cloneables:

public static <T extends Cloneable> List<T> cloneList(List<T> list)
{
    List<T> out = new ArrayList<T>();
    for(int i=0;i<list.size();i++)
    {
        out.add((T)((T)list.get(i)).clone());
    }
    return out;
}

which throws the error:

Helpers.java:40: error: cannot find symbol
            out.add((T)((T)list.get(i)).clone());
                                       ^
  symbol:   method clone()
  location: interface Cloneable

Why is that; isn't clone() the single method the Cloneable interface is all about?

Upvotes: 0

Views: 2445

Answers (3)

pbajpai
pbajpai

Reputation: 1369

Cloneable is a marker interface, clone() method is in Object class, So you should override clone() method in your class as per your requirement, and you also have to implement Cloneable interface to tell JVM that the object is cloneable. Cloneable interface works like Serializable interface which is for serialization.

Upvotes: 1

Manish
Manish

Reputation: 59

clone() is protected by default , could you please override it as public

Upvotes: 2

Idos
Idos

Reputation: 15310

You need to implement Cloneable and override clone() to use it (make it public, it's protected in the Object class).

Upvotes: 0

Related Questions