0

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?

Alexander
  • 19,906
  • 19
  • 75
  • 162
  • 1
    Did you look at the Javadoc of Cloneable? – Eran Jun 20 '16 at 07:02
  • @KarthikR The list should be able to contain any object type that implements the Cloneable interface. I think this is called "generics"... – Alexander Jun 20 '16 at 07:07
  • @KarthikR I made the method a static generic method as per http://stackoverflow.com/questions/4409100/how-to-make-a-java-generic-method-static – Alexander Jun 20 '16 at 07:10
  • 1
    Didn't note that it's a compilation error. Apologies. Will let u know. – Karthik R Jun 20 '16 at 07:11

3 Answers3

2

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

Manish
  • 59
  • 2
  • 8
1

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.

pbajpai
  • 1,303
  • 1
  • 9
  • 24
  • I want the method to consume ANY type that implements `Cloneable` interface - not necessarily a class I wrote by myself. – Alexander Jun 20 '16 at 07:17
  • @Alexander, I got your point, but the fact is to make a class Cloneable, there are two conditions, one is that Class must implement Cloneable interface and second point is that the class must override clone() method and make it as public, – pbajpai Jun 20 '16 at 07:25
  • I don't have a class, I only have a static method that should clone a list of cloneables. The cloneable should bring a way to clone it, and I just try to clone a list of these. – Alexander Jun 20 '16 at 07:33
0

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

Idos
  • 15,053
  • 14
  • 60
  • 75