Initialization of an ArrayList in one line
What are the different one-line initialization techniques that help us quickly create and populate ArrayLists for efficient coding?
Initializing an ArrayList in one line is a common need in Java when we want to quickly create and populate a list without writing multiple statements. Java offers different techniques depending on the Java version you are using and whether the list needs to be modifiable.
Some popular one-line initialization methods:
Using Arrays.asList()
List list = new ArrayList<>(Arrays.asList("A", "B", "C"));- Creates a modifiable ArrayList
- Simple and widely used
Using List.of() (Java 9+)
List list = new ArrayList<>(List.of("A", "B", "C"));- Convenient and concise
- List.of() returns an unmodifiable list, so we wrap it in ArrayList if modification is needed
Double-brace initialization
List list = new ArrayList() {{
add("A"); add("B"); add("C");
}};Very short but not recommended for large projects (creates anonymous inner class and memory overhead)
Using Collections.addAll()
List list = new ArrayList<>();
Collections.addAll(list, "A", "B", "C");Still clean and easy for adding multiple values
Why initialize in one line?
- Saves time while coding
- Keeps code more compact and readable
- Useful in testing, quick examples, and when creating small datasets
In conclusion, depending on the Java version and whether the list needs to be editable, you can choose the best one-line approach that fits your requirement while maintaining clean code structure.