10

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350
hafiz ali
  • 1,378
  • 1
  • 13
  • 33

2 Answers2

12

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).

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    I see i am using java 13 in my machine.should List.of work without problem? where else should i be changing the version if i am using intellij on windows machine – hafiz ali Aug 22 '20 at 10:18
  • @Hafizallylalani Make sure IntelliJ is really using Java 13 as an SDK; set the language level in the project and set the `sourceCompatibility` and `targetCompatibility` in gradle. – Mureinik Aug 22 '20 at 10:22
5

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?

Daly
  • 787
  • 2
  • 12
  • 23
  • As a possibility, Guava libraries includes an `ImmutableList` class (with `ImmutableList.of` method) if it were needed for an ancient JDK 8-based project. – BeardOverflow Jul 18 '23 at 12:50