How can I convert String
For a quick and efficient conversion of String[] to ArrayList<String>, make use of the Arrays.asList() method within a new ArrayList constructor as shown:
Key Insight: Arrays.asList() returns a fixed-size list backed by the underlying array. To get a fully modifiable ArrayList, it's crucial to wrap the result into a new ArrayList object.
Breaking down the conversion (with a little humor)
No magic involved, just plain old Java doing its thing. Let's understand this step by step:
Using Arrays.asList
The static utility class Arrays provides the function asList() to create a list backed by the initial array:
Step it up to ArrayList
The returned list is a fixed-length list. So, to make it flexible and modifiable - just like that stretchy pair of sweatpants we all own - simply instantiate a new ArrayList:
Add flair with Collections.addAll()
Instead of fumbling through each element like finding the car keys in your pocket, use Collections.addAll():
Stay old school with the for loop
Sometimes, we like it old-school, right? Maybe you want to add a twist of lemon to each fruit:
When you're feeling fancy with Streams
Java 8's Stream API can streamline things with a pinch of functional style:
Dealing with the peculiarities
Fixed-size list pitfall
When using Arrays.asList(), keep in mind that the resulting List is fixed in size and any attempt to modify it will throw an UnsupportedOperationException.
Null elements in the list
If the original array contains null entries, they'll also be part of the ArrayList. To avoid this, take advantage of the Streams API's filtering capability:
Synchronized ArrayList
The ArrayList instances created using the methods mentioned above aren't thread-safe. If multiple threads are going to access your ArrayList, consider using Vector or Collections.synchronizedList().
Was this article helpful?