I’ve seen how to declare an empty ArrayList, but I’m not sure how to java instantiate ArrayList with values directly. I tried the following code, but it returns a syntax error:
import java.io.IOException;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws IOException {
ArrayList<String> x = new ArrayList<String>();
x = ['xyz', 'abc']; // This line causes an error
}
}
What’s the correct syntax to initialize an ArrayList with predefined values?
Ah, I see what you’re trying to do, and I’ve been there myself when I was first learning! If you want to java instantiate ArrayList with values, the most common and reliable way is to use Arrays.asList()
. This will allow you to directly initialize an ArrayList
with values. Here’s the correct syntax:
import java.util.ArrayList;
import java.util.Arrays;
ArrayList<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
What’s happening here?
Arrays.asList()
creates a fixed-size list, but by wrapping it in new ArrayList<>(...)
, you make it mutable, which means you can still add or remove items if needed.
This is generally the go-to solution if you’re looking for something simple and efficient when you need to java instantiate ArrayList with values.
Great follow-up! While using Arrays.asList()
is solid, if you’re looking for a slightly more syntactically elegant or even a “quick-and-dirty” approach, you could try java instantiate ArrayList with values using an anonymous inner class. Here’s how you do that:
import java.util.ArrayList;
ArrayList<String> x = new ArrayList<String>() {{
add("xyz");
add("abc");
}};
FYI:
This is called double-brace initialization. It works fine for quick scripts or small projects, but it does come with a small caveat: the anonymous class can introduce some unnecessary memory overhead, so it’s something to avoid for performance-critical applications.
Still, it’s pretty neat if you just need to java instantiate ArrayList with values in a concise way and don’t mind the trade-offs!
Great points already! One more thing I’d add if you’re on Java 9 or higher: there’s a super clean and modern way to java instantiate ArrayList with values, but with a small restriction. If you don’t need to modify the list later, you can use List.of()
to quickly create an unmodifiable list:
import java.util.List;
List<String> x = List.of("xyz", "abc");
Heads-up:
This creates an immutable list, so you can’t add or remove items afterward, but it’s perfect if you just need to initialize your list once and keep it intact. It’s super clean and concise for cases where you don’t need mutability, and it’s a great alternative when you want to java instantiate ArrayList with values in modern Java.