Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.of gives error: cannot find symbol error

I am using springboot with gradle and I am trying to execute below code in the controller.

List<String> planets
    = List.of("Mercury", "Venus", "Earth", "Mars",
    "Jupiter", "Saturn", "Uranus", "Neptune");

On compiling I get the following error

error: cannot find symbol = List.of("Mercury", "Venus", "Earth", "Mars", ^ symbol: method of(String,String,String,String,String,String,String,String)
location: interface List

my gradle file has

sourceCompatibility = '1.8'

I do understand that its a java 9 feature but unsure why would it fail on compile

like image 975
hafiz ali Avatar asked Aug 22 '20 08:08

hafiz ali


2 Answers

List.of isn't a Java 9 feature, it's a method that was added in JDK 9. If you're using JDK 8, it just doesn't contain this method, and thus can't compile against it.

In short - use a newer JDK (and set the compatibility levels to 9 while you're at it, so you don't create a mix of valid Java 8 program that can only work with a newer JDK).

like image 163
Mureinik Avatar answered Oct 17 '22 06:10

Mureinik


A quick fix is to replace List.of with Arrays.asList which is in JDK 8.

Note these methods are not quite identical, List.of returns an immutable list whereas Arrays.asList returns a mutable list. There are a few other differences listed here:

What is the difference between List.of and Arrays.asList?

like image 1
Daly Avatar answered Oct 17 '22 06:10

Daly