1

I was wondering, which is a recommended way to convert list to array, as both methods just seems to work fine.

As from Converting 'ArrayList<String> to 'String[]' in Java, I saw new String[list.size()] way is recommend, but I'm not sure why.

list.toArray(new String[0]);

list.toArray(new String[list.size()]);
Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

5

If you pass an array of size 0, toArray() will need to use reflection to create a new array instance of the same type.
That is slow.

If you pass a correctly-sized array, it can simply use the array instance that you passed, so it won't need to do any extra work.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Why does it need to use reflection to allocate an array of the right size? Wouldn't it just run the same code that Cheok's got in his second line? – Nathaniel Waisbrot Jun 02 '13 at 16:36
  • @NathanielWaisbrot Cheok's code is specialized for the case of a String array. toArray() has to create a correctly sized array of the same type as its argument, whatever that is. – Patricia Shanahan Jun 02 '13 at 16:48
  • Why reflection, generic type cast will do perfectly? I can't see why reflection is required, I think you're mistaking. – Mordechai Jun 03 '13 at 03:11
  • @MouseEvent: You're forgetting about type erasure. That isn't possible. – SLaks Jun 03 '13 at 13:29
  • Interesting. Java IDE IntelliJ IDEA has a code inspection that will helpfully recommend this. It doesn't explain why it suggests it though. – JeroenHoek Dec 11 '13 at 16:46