1

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?

Aviv Cohn
  • 11,431
  • 20
  • 52
  • 95

2 Answers2

4
ArrayList<Stuff<Thing>> thingsList = new ArrayList<Stuff<Thing>>();
Stuff<Thing>[] array = (Stuff<Thing>[] )thingsList.toArray(new Stuff[0]);
satellite779
  • 121
  • 2
2

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.

EpicPandaForce
  • 71,034
  • 25
  • 221
  • 371