简体   繁体   English

如何将通用列表转换为数组?

[英]How can I convert a generic list to an array?

I'm beginning to discover the wonders of Java generics... 我开始发现Java泛型的奇迹...

Apparently, you can't create a generic array: 显然,您无法创建通用数组:

Stuff<Thing>[] array = new Stuff<Thing>[5]; // doesn't compile

So obviously, you can't do this either (which works perfectly when generics aren't involved): 因此,很明显,您也不能这样做(在不涉及泛型的情况下,效果很好):

// thingsList is an ArrayList<Stuff<Thing>>
Stuff<Thing>[] array = thingsList.toArray(new Stuff<Thing>[0]);

So my question is, how can I get around this? 所以我的问题是,我该如何解决? How can I easily convert a generic list to an array? 我如何轻松地将泛型列表转换为数组?

ArrayList<Stuff<Thing>> thingsList = new ArrayList<Stuff<Thing>>();
Stuff<Thing>[] array = (Stuff<Thing>[] )thingsList.toArray(new Stuff[0]);

It would be the following: 将会是以下内容:

Stuff<Thing>[] array = thingsList.toArray(new Stuff<Thing>[thingsList.size()]);

However, it is a restriction on Generics that you can't make parametrized arrays, see http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays 但是,对泛型的限制是您无法创建参数化数组,请参见http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays

So only the following would work: 因此,只有以下内容可以工作:

Stuff[] array = thingsList.toArray(new Stuff[thingsList.size()]);

But that's a raw type. 但这是原始类型。

Therefore, it's recommended to just use a List<Stuff<Thing>> instead rather than an array. 因此,建议仅使用List<Stuff<Thing>>而不是数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM