What is the best way to initialize an ArrayList in one line in Java?
I’m trying to create a list of options for testing purposes. Initially, I used this approach:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Then I refactored it to this:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a more efficient or cleaner way to initialize an ArrayList with multiple elements in a single line of Java code?
The best way to initialize an ArrayList in one line depends on your Java version and whether you need a mutable or immutable list. For most use cases, including testing scenarios, you should use either new ArrayList<>(Arrays.asList(...)) for Java 8 and earlier, or new ArrayList<>(List.of(...)) for Java 9+.
Contents
- Traditional Arrays.asList() Approach
- Modern List.of() Method (Java 9+)
- Stream API Approach (Java 8+)
- Double-Brace Initialization
- Comparison of Methods
- Recommendations for Testing
- Performance Considerations
Traditional Arrays.asList() Approach
The Arrays.asList() method has been available since Java 1.2 and is the most commonly used approach for initializing a list with multiple elements. However, it’s important to understand its limitations.
// This creates a fixed-size list that cannot be modified
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
// To get a mutable ArrayList, wrap it:
ArrayList<String> mutablePlaces = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Key characteristics:
- Returns a
Listinterface, not anArrayListimplementation - Creates a fixed-size list that doesn’t allow adding or removing elements
- The list is backed by the original array, so changes to array elements are reflected in the list
- Available in all Java versions
As Stack Overflow explains, “Arrays.asList() returns java.util.List and not ArrayList orLinkedList. Another worth noting point is that List returned by Arrays.asList() is a fixed-length list that doesn’t allow you to add or remove elements from it.”
Modern List.of() Method (Java 9+)
Java 9 introduced List.of() as a more convenient and safer alternative to Arrays.asList() for creating immutable lists.
// Creates an immutable list
List<String> immutablePlaces = List.of("Buenos Aires", "Córdoba", "La Plata");
// To get a mutable ArrayList, wrap it:
ArrayList<String> mutablePlaces = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Key characteristics:
- Returns an immutable list (cannot be modified after creation)
- Supports null values (unlike Set.of() and Map.of())
- More memory efficient than Arrays.asList()
- Cleaner syntax and type-safe
- Available from Java 9+
As Baeldung states, “In contrast to Arrays.asList(), Java 9 introduced a more convenient method, List.of()”
Stream API Approach (Java 8+)
Java 8 and later versions support using the Stream API to create lists, which can be useful for more complex initialization scenarios.
// Using Stream.of() with toList() (Java 16+)
List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").toList();
// Using collect() (Java 8+)
List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata")
.collect(Collectors.toList());
// To get ArrayList specifically
ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata")
.collect(Collectors.toCollection(ArrayList::new));
Key characteristics:
- Flexible for complex initialization logic
- Available from Java 8+
- Java 16+ provides a simplified
toList()method - More verbose than other approaches for simple cases
Double-Brace Initialization
This approach uses an anonymous inner class with an instance initializer, though it’s generally considered an anti-pattern.
ArrayList<String> places = new ArrayList<String>() {{
add("Buenos Aires");
add("Córdoba");
add("La Plata");
}};
Key characteristics:
- Creates unnecessary anonymous inner class
- Can cause memory leaks due to hidden reference
- Considered an anti-pattern by most Java experts
- Not recommended for production code
As Academic Help notes, “double-brace initialization is considered an anti-pattern and should be used with caution.”
Comparison of Methods
| Method | Java Version | Mutability | Null Support | Performance | Best For |
|---|---|---|---|---|---|
Arrays.asList() |
All | Fixed-size | Yes | Good | Backward compatibility |
List.of() |
9+ | Immutable | Yes | Excellent | Modern Java, immutable lists |
Stream.of().toList() |
16+ | Immutable | Yes | Good | Complex initialization |
Stream.of().collect() |
8+ | Mutable | Yes | Good | Complex mutable initialization |
| Double-brace | All | Mutable | Yes | Poor | Legacy code (avoid) |
Recommendations for Testing
For your testing scenario, here are the best approaches based on your Java version:
Java 8 and earlier:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Java 9 and later:
ArrayList<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
For immutable test data:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
As BeginnersBook explains, “In Java 9 and later, you can use List.of() to create an immutable list and then pass it to the ArrayList constructor if you need a mutable list.”
Performance Considerations
For testing purposes, performance differences are usually negligible, but here are some general guidelines:
List.of()is generally the most efficient for immutable listsArrays.asList()has good performance but creates fixed-size lists- Stream approaches have slightly more overhead due to the stream pipeline
- Double-brace initialization has the worst performance due to anonymous class creation
As Baeldung demonstrates, “The original array and the list share the same references to the objects” when using Arrays.asList(), which can be both an advantage and a consideration for testing.
Conclusion
For initializing an ArrayList with multiple elements in one line:
- If you’re using Java 9+: Use
new ArrayList<>(List.of(...))for the cleanest, most efficient mutable ArrayList - If you’re using Java 8 or earlier: Use
new ArrayList<>(Arrays.asList(...))for backward compatibility - For immutable test data: Use
List.of(...)directly if you don’t need to modify the list - Avoid: Double-brace initialization due to its anti-pattern status
Your current refactored approach using Arrays.asList() is perfectly fine for Java 8 and earlier, and you should consider upgrading to List.of() when you move to Java 9+ for better type safety and performance.
Sources
- Stack Overflow - Initialization of an ArrayList in one line
- Baeldung - Java List Initialization in One Line
- Baeldung - Difference Between Arrays.asList() and List.of()
- BeginnersBook - How to Initialize an ArrayList in Java
- Academic Help - How to Initialize a List in Java
- CodeJava - Java Initialize ArrayList with Values in One Line
- Java2Blog - Initialize ArrayList with values in Java