如何初始化我的通用数组? [英] How can I initialize my generic array?
本文介绍了如何初始化我的通用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个 ArrayLists 数组:
I want to have an array of ArrayLists:
ArrayList<MyClass>[] myArray;
我想用下面的代码来初始化:
I want to initialize it by the following code:
myArray = new ArrayList<MyClass>[2];
但我收到此错误:
Cannot create a generic array of ArrayList<MyClass>
如何初始化?
推荐答案
这在 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 ArrayList
s:
ArrayList<ArrayList<MyClass>> lists = new ArrayList<ArrayList<MyClass>>(2);
我会推荐后者.
这篇关于如何初始化我的通用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文