Can't assign to a typed variable an INode

2020-06-27 13:02发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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.



标签: java generics