2

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

devoured elysium
  • 101,373
  • 131
  • 340
  • 557

3 Answers3

3

T is an INode but INode is not a T. So you can't put the result of INode.clone() (Object or Inode) into a list of T. That's why you need a cast

Regards

diodfr
  • 99
  • 3
0

First, I suppose that INode is an interface, so the clone() method shouldn't be available directly because it is defined in Object. You should define a clone() method in the interface or make INode extend Cloneable then cast the cloned Node to T.

Furthermore, you as I wrote, you need to cast your cloned object to T because you know that both T and the clone are instances of INode but you are not sure that the clone is an instance of T.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
0

First, I suspect you haven't re-declare the clone method in INode class and implements interface Cloneable.

Besides, a cast to T is required in order to insert the clone into parameterized list.

Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83