Create ArrayList
from array
To transform an array into a ArrayList
swiftly, employ the Arrays.asList()
function wrapped with a constructor:
Remember: Arrays.asList()
in its pure form implies an immutable list. Enveloping it with new ArrayList<>()
guarantees that it becomes modifiable.
Deeper insights
The philosophy of Arrays.asList()
The utility Arrays.asList()
is a tremendous shortcut for initializing a list from an array. However, it comes with a peculiarity: the generated list is immutable and linked to the original array like Siamese twins. When you alter one, the other mirrors it.
Primitives: The troublemakers
Primitives like int[]
unceremoniously disrupt the flow when used with Arrays.asList()
. Autoboxing, or automatic conversion from primitive to wrapper, is not supported. The workaround for these rebels is making use of Java 8 streams for boxing purpose.
The Guava to the rescue
Here comes the Guava library, our supercharged toolbox. To effortlessly create a modifiable ArrayList
, use Lists.newArrayList(array)
. Need an immutable list? Don't fret, ImmutableList.copyOf(array)
has got you covered.
Leveraging Java 7's diamond
Keeping up with the evolution is crucial in Java. The diamond operator <>
removes redundant type specification on RHS, making the code cleaner and faster to write.
Advanced techniques and alternatives
Freeze! Collections.unmodifiableList
If utter immutability is what you seek, Collections.unmodifiableList()
is your bulwark against any unwelcomed alterations.
Varargs and Arrays.asList()
: The dynamic duo
An underappreciated feature of Arrays.asList()
is accepting varargs for a sleek inline list creation.
Custom type arrays: Isn't it straightforward?
For custom type arrays, the conversion process is plain sailing. However, beware of ClassCastException
! Ensure type consistency to keep this trouble at bay.
DIY: Create ArrayList manually
One must never forget the roots! If it wasn't for the manual iteration, none of this would have been possible. This good old method comes in handy whenever complex conversion logic arises.
Was this article helpful?