I'm wondering why the following code fails to work:
public static <T extends INode> List<T> cloneList(List<T> list) {
List<T> result = new ArrayList<T>(list.size());
for (T t : list)
result.add(t.clone()); <--- problem here
return result;
}
INode.clone()
has INode
return type, and we know that every T must implement INode
, so I'm surprised the above code doesn't compile. Is there any semantic problem with what I'm showing above?
EDIT: Maybe because at compile time Java will erase the generic type and a cast is then still needed? Couldn't the compiler have done that for me?
EDIT2: Here's INode
:
public interface INode {
INode accept(Visitor visitor);
INode clone();
}
Thanks