Converting 'ArrayList to 'String
Make the ArrayList<String> to String[] transformation in one swoop:
The toArray(new String[list.size()]) variant gives you a suitably sized String[] array from your ArrayList<String>. The need for manual array construction or iteration is handsomely covered by our "**toArray() butler service".
Making Java 11+ proud
For those operating on Java 11+, put this chap to work:
Making use of toArray(IntFunction<T[]> generator), Java 11's secret sauce, with String[]::new working like an array's constructor, scooping the type right and relishing in the JVM's optimized embrace.
Exploring additional paths and corner cases
Stream API to the rescue
For the hipsters who were there when Java 8 announced the Stream API, give this snappy solution a spin:
Ideal when you fancy some filtering, mapping, or other transformations before the switchboard conversation takes place.
Speaking ‘Immutable’
Java 9 introduced List.of, the Harry Potter spell for conjuring immutable lists:
The old-school loop
And then, there are times when control freak mode gets the better of you or when teaching the rookies:
Array copy, ready!
Finally, turn to Arrays.copyOf when you want to feel adventurous:
Overkill for simple conversions, and less efficient than list.toArray(new String[0]) by the way.
Type correctness or nothing!
When dealing with a non-generic ArrayList you're pretty sure only houses String objects, do the casting ClassCastException dance:
Just remember to make sure you're not kicking down an open door by stuffing in non-String objects in there.
Satiate your visual hunger
Picturing it can be a charm. What if you're at a train station where each passenger is a String just aching to hop on the String[] train from the ArrayList<String> platform:
Time for boarding:
And the String[] train after the operation:
It's a smooth ride from the ArrayList<String> platform to the String[] train. No turbulence on this flight!
Riding the JVM's optimization wave
Modern JVM versions got a soft spot for toArray(new String[0]). Even if it might not come off as intuitive, using new String[0] could potentially leave pre-sizing the array in the dust, thanks to internal JVM optimization.
Valuing readability
The case for list.toArray(new String[list.size()]) might seem more persuasive owing to readability or logical flow. Still, the rhythm of new String[0] is tuned better with the JVM's performance optimization mantra.
Was this article helpful?
