Aviv Cohn
Aviv Cohn

Reputation: 17183

How can I convert a generic list to an array?

I'm beginning to discover the wonders of Java generics...

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?

Upvotes: 1

Views: 107

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81539

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

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.

Upvotes: 2

satellite779
satellite779

Reputation: 121

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

Upvotes: 4

Related Questions