Abdul D.
—I don’t know how to initialize a List<String>
object in Java.
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:
ArrayList
classArrays.asList()
methodList.of()
methodNote: The List.of()
method can only be used with with Java 9+.
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.
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.
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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.