NeuroAgent

Best Way to Initialize ArrayList in One Line in Java

Learn the best methods to initialize ArrayList in one line in Java. Compare Arrays.asList(), List.of(), Stream API, and more. Find the perfect approach for your Java version and testing needs.

Question

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:

java
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then I refactored it to this:

java
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?

NeuroAgent

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

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.

java
// 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 List interface, not an ArrayList implementation
  • 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.

java
// 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.

java
// 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.

java
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:

java
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Java 9 and later:

java
ArrayList<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

For immutable test data:

java
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 lists
  • Arrays.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:

  1. If you’re using Java 9+: Use new ArrayList<>(List.of(...)) for the cleanest, most efficient mutable ArrayList
  2. If you’re using Java 8 or earlier: Use new ArrayList<>(Arrays.asList(...)) for backward compatibility
  3. For immutable test data: Use List.of(...) directly if you don’t need to modify the list
  4. 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

  1. Stack Overflow - Initialization of an ArrayList in one line
  2. Baeldung - Java List Initialization in One Line
  3. Baeldung - Difference Between Arrays.asList() and List.of()
  4. BeginnersBook - How to Initialize an ArrayList in Java
  5. Academic Help - How to Initialize a List in Java
  6. CodeJava - Java Initialize ArrayList with Values in One Line
  7. Java2Blog - Initialize ArrayList with values in Java