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?
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);
}
}
Why use this?
Fast random access (
O(1)
for get()
operations).
Automatically resizes itself when needed.
Ideal for storing ordered collections where retrieval speed is key.
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);
}
}
Why use this?
Fast insertions & deletions (
O(1)
when modifying the beginning/middle).
Works well for queue-based operations (FIFO, LIFO).
Avoids costly resizing operations that happen in
ArrayList
.
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);
}
}
Why use this?
Best for read-only collections (prevents accidental modification).
More memory-efficient as it’s immutable.
Cleaner syntax for creating a list in one line.
When to avoid?
If you need to modify the list (add/remove elements), this approach won’t work as it throws UnsupportedOperationException
.