通用列表和通用数组 [英] Generic List and Generic Array

查看:128
本文介绍了通用列表和通用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


我有以下代码:

  class B< X> 
{
public void create()
{
List< X> l1 = new ArrayList< X>(); //无错误

X [] arrr = new X [10]; //错误
}
}

我知道我不能实例化一个Generic阵列由于类型擦除。但为什么我可以实例化一个泛型列表的实例?

原因是泛型使用类型擦除来实现: p>

没有类型 X 在运行时是已知的。这意味着你不能实例化一个数组(未知类型)。



但是由于你不需要(实际上不能使用)类型用于在运行时创建参数化类型的信息(再次:类型擦除),创建 ArrayList< X> 不成问题。 b

请注意,在内部, ArrayList 总是对于实际使用 Object [] 存储,不管类型参数是什么。


Possible Duplicate:
What is the easiest alternative to a generic array in Java?

I have the following code:

class B<X>
{
    public void create()
    {
        List<X> l1 = new ArrayList<X>(); //No ERROR

        X[] arrr = new X[10];   //ERROR
    }
}

I know that I cannot instantiate a Generic array due to type erasure. But why can I instantiate an instance of a generic List?

解决方案

The reason is that generics are implemented using type erasure:

No type X is known at runtime. That means that you can't instantiate an array of that (unknown type).

But since you don't need (and in fact can't use) the type information for creating a parameterized type at runtime (again: type erasure), creating an ArrayList<X> is not a problem.

Note that internally an ArrayList always uses an Object[] for actual storage, no matter what the type argument is.

这篇关于通用列表和通用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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