How do I initialize a `List<String>` object in Java?
The Problem
I don’t know how to initialize a List<String> object in Java.
The Solution
Depending on your needs and the Java version you’re using, there are multiple ways to initialize a List<String> object.
We’ll demonstrate how to use the following:
- The
ArrayListclass - The
Arrays.asList()method - The
List.of()method
Note: The List.of() method can only be used with with Java 9+.
Using ArrayList
The most common way to initialize a List<String> is to use an ArrayList, which is part of the java.util package:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");
System.out.println("My List: " + myList);
}
}
In this example, myList is an instance of ArrayList that holds String elements. The add() method adds items to the list.
Using Arrays.asList()
Alternatively, you can use Arrays.asList() to initialize a List with predefined values:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Apple", "Banana", "Cherry");
System.out.println("My List: " + myList);
}
}
The Arrays.asList() method creates a fixed-size list, meaning you cannot add or remove elements after initialization.
Using List.of()
If you are using Java 9 or later, you can use List.of() to create an immutable list:
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> myList = List.of("Apple", "Banana", "Cherry");
System.out.println("My List: " + myList);
}
}
Lists created with the List.of() method are immutable, meaning you cannot add, remove, or modify list elements after initialization.
Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.