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
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"));
You can use Google guava library. It has lot of utility methods for this like
List<String> list = Lists.newArrayList(....)
With java 9 you can do the same as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With