Creating a List in Java: Best Approaches

How do you make a list in Java?

In Java, we create a Set using new HashSet(), but what is the correct way to make a list in Java? Are there multiple approaches, and which one is recommended for different use cases?

One of the most common and flexible ways to make a list in Java is by using ArrayList. It allows dynamic resizing and is generally the go-to choice for most scenarios.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("New York");
        cities.add("Los Angeles");
        cities.add("Chicago");

        System.out.println(cities);
    }
}

:white_check_mark: Why use this? :heavy_check_mark: Fast random access (O(1) for get() operations). :heavy_check_mark: Automatically resizes itself when needed. :heavy_check_mark: Ideal for storing ordered collections where retrieval speed is key.

:rotating_light: When to avoid? If you frequently add/remove elements from the middle of the list, LinkedList might be a better option.

That’s a great start! But if your use case involves frequent insertions or deletions, how to make a list in Java with LinkedList might be a smarter choice.

import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> tasks = new LinkedList<>();
        tasks.add("Write code");
        tasks.add("Test software");
        tasks.add("Deploy application");

        System.out.println(tasks);
    }
}

:white_check_mark: Why use this? :heavy_check_mark: Fast insertions & deletions (O(1) when modifying the beginning/middle). :heavy_check_mark: Works well for queue-based operations (FIFO, LIFO). :heavy_check_mark: Avoids costly resizing operations that happen in ArrayList.

:rotating_light: When to avoid? If you need fast random access, ArrayList is far better since LinkedList requires traversing nodes to find an element.

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.