shanlodh
shanlodh

Reputation: 1045

ArrayList initialization through List.of()

From Core Java for the Impatient:

... there is no initializer syntax for array lists. The best you can do is construct an array list like this:

ArrayList<String> friends =  new ArrayList<>(List.of("Peter", "Paul"));

But when I'm try compiling this code getting error:

error: cannot find symbol
                ArrayList<String> friends = new ArrayList<>(List.of("Peter", "Paul"));
                                                            ^
  symbol:   variable List

My imports are:

import java.util.List;
import java.util.ArrayList;

Thanks

Upvotes: 19

Views: 61683

Answers (1)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13833

import java.util.ArrayList;
import java.util.List;

// ...
ArrayList<String> friends =  new ArrayList<>(List.of("Peter", "Paul"));

Is perfectly fine assuming you're running at least Java 9.


Prior to Java 9, you need to go for Arrays.asList() instead of List.of():

ArrayList<String> friends =  new ArrayList<>(Arrays.asList("Peter", "Paul"));

Upvotes: 26

Related Questions