0

First time using generics.

I've successfully created an ArrayList of generic objects, and I would like to convert it to a regular array T[].

Normally, this is something like

String[] x = (String[])myStrings.toArray(new String[0])

However, in this case, replacing String with T does not work. i.e.

return (T[]) ret.toArray(T[0]);

Here is complete code for my method, tho not sure it is relevant: https://puu.sh/AzxKD/f525bdbe77.png

khelwood
  • 46,621
  • 12
  • 59
  • 83
  • Hint: in the other question, read the "Checked" part, as you do have access to `Class` in your method – Joachim Sauer Jun 05 '18 at 14:54
  • Note the signature of `List.toArray(target)`: ` T[] toArray(T[] target)`. That means in `(String[])myStrings.toArray(new String[0])` the cast is not necessary. – Thomas Jun 05 '18 at 14:58

1 Answers1

1

You can't create an array with new T[size] for a generic type variable T. Java doesn't support it.

You can cast an Object[] array to T[], and for most purposes that's fine.

In this case, that would be:

return (T[]) ret.toArray();
khelwood
  • 46,621
  • 12
  • 59
  • 83
  • Thank you - So there is no other way but to return an array of Objects? I feel this defeats the purpose as I will not have t o convert this Object array to the correct class type – Greg Bengis Jun 07 '18 at 13:57
  • I ended up working around this cast with the following: `code` T[] rett = (T[])Array.newInstance(thisClass, ret.size()); for (int i = 0; i < rett.length; i++) { rett[i] = thisClass.cast(ret.get(i)); } `code` – Greg Bengis Jun 07 '18 at 14:11
  • @GregBengis It is not very helpful to try and put code in comments, but yes, if you have access to a `Class` object then you can use `Array.newInstance`. – khelwood Jun 07 '18 at 14:13
  • Yeah the code was a fail.. haha. Tho it wasn't too much. Thanks for your help, learning a lot about this stuff.. – Greg Bengis Jun 07 '18 at 15:27