How to declare an ArrayList with values?
Want quick results? Pre-fill an ArrayList
using:
Initialization Block:
Arrays.asList:
Either way leads to an ArrayList
with elements "A", "B", and "C".
Untangling the methods of ArrayList declaration
Let's divide and conquer with some understandable code snippets to illustrate different declaration methods.
Java 9+ and Java 8: The cool guys on the block
Java 9+ has an edge with List.of()
- it creates an immutable list. No changes allowed!
Java 8 rocks the Stream
for a mutable list.
Ensuring list mutability for changes on the go
If you need to make changes on the go, say hello to ArrayList
:
Minimizing clutter with static imports and Guava
Use static import to cut corners:
Guess what? Guava just made the list (pun definitely intended):
Remember to import:
Using generics for type safety
Type safety is a big deal:
Mutable vs Immutable
List.of()
means no changes allowed.
For modifiable gang, use ArrayList
.
Initial capacities for performance tuning
If you know list size beforehand set an initial capacity.
Deeper into list declaration approaches
Unravel more conceptual knots on array initialization for common and edge scenarios.
Converting arrays to lists
No Hogwarts degree necessary for this magic trick:
Declaring with List Interface
If you don't need ArrayList methods, use the List
interface:
Immutable lists aren't always your friend
Beware! Immutable lists throw tantrums (read: UnsupportedOperationException
) if you try to change them. Stick to mutable lists for changing collections.
Was this article helpful?