ArrayList的内部T []数组的实例化 [英] ArrayList's instantiating of the inner T[] array

查看:70
本文介绍了ArrayList的内部T []数组的实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,如果您有一个泛型类,且该类的数组取决于该类的类型参数,则无法以通常的方式初始化该数组:

I've found out that if you have a generic class with an array that depends of type parameter of that class, you can't initialize that array in a usual way:

class Foo<T>  {
    private T[] a;

    Foo()  {
       a=new T[5]; //doesn't compile
    }
}

您只能执行以下操作:

class Foo<T>  {
        private T[] a;

        Foo(T[] a)  {
           this.a=a;
        }
    }

但是此代码是可能的:

ArrayList<Integer> list=new ArrayList<>();

为什么? ArrayList如何克服这一问题?我已经研究了它的代码,但无法弄清楚.似乎只是将内容存储在Object[]数组中,这似乎是错误的.

Why? How does the ArrayList overcome that thing? I've looked into its code but couldn't figure it out. It seems like it just stores things in Object[] array which seems wrong.

推荐答案

将此视为一个比喻:

您拥有一家铅笔公司.您用货车上的铅笔四处行驶.

You own a pencil company. You drive around with pencils in your van.

您可以在面包车中放些花:毕竟,这是一辆面包车,因此您可以在其中放任何想要的东西.棒球,大猩猩,氦气球.

You could put flowers in your van: it's a van, after all, so you could put anything you want (that fits) in there. Baseballs, gorillas, helium balloons.

但是您选择不这样做:您是一家铅笔公司,所以您放进货车的所有东西都是铅笔.如果您来自汉堡公司的朋友要您在面包车中放一些汉堡肉饼,您会说不:这辆面包车仅用于铅笔.

But you choose not to: you're a pencil company, so all you put into your van is pencils. If your friend from the burger company asks you to put some burger patties in your van, you will say no: this van is only for pencils.

因此,当您从面包车中拿出东西时,您会知道它会是一支铅笔,因为您确定穿过这些门的唯一东西是一支铅笔.

So, when you come to take something out of your van, you know it's going to be a pencil, because you made sure the only thing that went in through those doors was a pencil.

ArrayList<T>也是如此:您可以将任何内容存储在该Object[]中,但是您不能:您只能在其中存储T,因为您可以只能通过add(T)addAll(Collection<? extends T>)方法向其中添加内容.

And so it is with an ArrayList<T>: you could store anything in that Object[], but you don't: you can only store Ts in there, because you can only add things to it through the add(T) or addAll(Collection<? extends T>) methods.

因此,将元素存储在Object[]中而不是存储在更具体类型的数组中并不重要:唯一会从ArrayList<T>中获得的东西-通过其get()(等)方法-是T或其子类型之一的实例.

So it doesn't matter that your elements are being stored in an Object[], rather than more-specifically typed array: the only things that you'll get out of an ArrayList<T> - via its get() (etc) methods - are instances of T, or one of its subtypes.

这篇关于ArrayList的内部T []数组的实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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