Creating a List in Java: Best Approaches

Both ArrayList and LinkedList are great, but what if you don’t want to modify the list at all? In that case, how to make a list in Java using List.of() is the perfect solution for immutable collections.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> colors = List.of("Red", "Green", "Blue");

        System.out.println(colors);
    }
}

:white_check_mark: Why use this? :heavy_check_mark: Best for read-only collections (prevents accidental modification).

:heavy_check_mark: More memory-efficient as it’s immutable.

:heavy_check_mark: Cleaner syntax for creating a list in one line.

:rotating_light: When to avoid?

If you need to modify the list (add/remove elements), this approach won’t work as it throws UnsupportedOperationException.