Sentry Answers>Java>

How do I initialize a `List<String>` object in Java?

How do I initialize a `List<String>` object in Java?

Abdul D.

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 ArrayList class
  • 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:

Click to Copy
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:

Click to Copy
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:

Click to Copy
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.

  • Sentry BlogException Handling in Java (with Real Examples)
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “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.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.