Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList initialization through List.of()

Tags:

java

arraylist

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

like image 249
shanlodh Avatar asked Jun 29 '18 12:06

shanlodh


2 Answers

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"));
like image 133
Grzegorz Piwowarek Avatar answered Sep 28 '22 03:09

Grzegorz Piwowarek


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.

like image 21
pvpkiran Avatar answered Sep 28 '22 02:09

pvpkiran