我怎么能初始化我一般数组? [英] How can I initialize my generic array?

查看:147
本文介绍了我怎么能初始化我一般数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有的ArrayList的数组:

I want to have an array of ArrayLists:

ArrayList<MyClass>[] myArray;

我想通过以下code将其初始化:

I want to initialize it by the following code:

myArray = new ArrayList<MyClass>[2];

但我得到这个错误:

But I get this error:

Cannot create a generic array of ArrayList<MyClass>

我怎么能初始化呢?

How can I initialize it?

推荐答案

这是不严格可能在Java中并没有得到实施至今。

This is not strictly possible in Java and hasn't been since its implementation.

您可以解决它像这样:

ArrayList<MyClass>[] lists = (ArrayList<MyClass>[])new ArrayList[2];

这可能(实际上,它应该)生成一个警告,但没有其他的办法来解决它。在所有诚实,你会过得更好,以创建一个的ArrayList 的ArrayList 取值:

This may (really, it should) generate a warning, but there is no other way to get around it. In all honesty, you would be better off to create an ArrayList of ArrayLists:

ArrayList<ArrayList<MyClass>> lists = new ArrayList<ArrayList<MyClass>>(2);

后者是什么,我会推荐。

The latter is what I would recommend.

这篇关于我怎么能初始化我一般数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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