227

ArrayList or List declaration in Java has questioned and answered how to declare an empty ArrayList but how do I declare an ArrayList with values?

I've tried the following 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'];
    }
}
ישו אוהב אותך
  • 26,433
  • 11
  • 70
  • 92
alvas
  • 105,505
  • 99
  • 405
  • 683

6 Answers6

437

In Java 9+ you can do:

var x = List.of("xyz", "abc");
// 'var' works only for local variables

Java 8 using Stream:

Stream.of("xyz", "abc").collect(Collectors.toList());

And of course, you can create a new object using the constructor that accepts a Collection:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList class:

Maroun
  • 91,013
  • 29
  • 181
  • 233
38

Use:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):

List<String> x = Arrays.asList("xyz", "abc");

Note: you can also use a static import if you like, then it looks like this:

import static java.util.Arrays.asList;

...

List<String> x = new ArrayList<>(asList("xyz", "abc"));

or

List<String> x = asList("xyz", "abc");
Puce
  • 36,099
  • 12
  • 75
  • 145
28

You can do like this :

List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));
Vimal Bera
  • 10,155
  • 4
  • 23
  • 47
11

The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.

Example:

ArrayList<String> list = newArrayList("a", "b", "c");

(This assumes import static com.google.common.collect.Lists.newArrayList;)

Lii
  • 10,777
  • 7
  • 58
  • 79
9

Try this!

List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));

It's a good practice to declare the ArrayList with interface List if you don't have to invoke the specific methods.

Drogba
  • 3,986
  • 4
  • 20
  • 29
6

Use this one:

ArrayList<String> x = new ArrayList(Arrays.asList("abc", "mno"));
Rajendra arora
  • 2,106
  • 1
  • 15
  • 23