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?

4
  • 1
    Did you look at the Javadoc of Cloneable? Commented Jun 20, 2016 at 7:02
  • @KarthikR The list should be able to contain any object type that implements the Cloneable interface. I think this is called "generics"... Commented Jun 20, 2016 at 7:07
  • @KarthikR I made the method a static generic method as per stackoverflow.com/questions/4409100/… Commented Jun 20, 2016 at 7:10
  • 1
    Didn't note that it's a compilation error. Apologies. Will let u know. Commented Jun 20, 2016 at 7:11

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I want the method to consume ANY type that implements Cloneable interface - not necessarily a class I wrote by myself.
@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,
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.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.