无法分配给< T扩展INode>键入变量INode类型值。为什么? [英] Can't assign to a <T extends INode> typed variable an INode type value. Why?

查看:90
本文介绍了无法分配给< T扩展INode>键入变量INode类型值。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static< T extends INode> 

我想知道为什么下面的代码无法工作:列表与LT; T> cloneList(List< T>列表){
List< T> result = new ArrayList< T>(list.size()); (t T:list)

result.add(t.clone()); < ---这里的问题

返回结果;

INode.clone() INode 返回类型,并且我们知道每个T必须实现 INode ,所以我很惊讶上面代码不能编译。有什么语义问题,我上面显示的是什么?编辑:也许是因为在编译时Java将擦除泛型类型,然后仍然需要一个演员?编译器不能为我做到这一点吗?



编辑2:这是 INode

  public interface INode {
INode accept(Visitor visitor);
INode clone();

谢谢

解决方案

T是一个INode,但INode不是T.
所以你不能把INode.clone()(Object或Inode)的结果放到T的列表中。
这就是为什么你需要演员



问候


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

解决方案

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

这篇关于无法分配给&lt; T扩展INode&gt;键入变量INode类型值。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆