`List.of`出现错误:无法找到符号错误。

huangapple go评论64阅读模式
英文:

List.of gives error: cannot find symbol error

问题

以下是翻译好的部分:

我正在使用带有Gradle的Spring Boot,并尝试在控制器中执行以下代码。

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

在编译时,我收到以下错误消息:

错误:找不到符号
= List.of("Mercury", "Venus", "Earth", "Mars",
^ 符号: 方法 of(String,String,String,String,String,String,String,String)
位置:接口 List

我的Gradle文件中有:

sourceCompatibility = '1.8'

我理解这是Java 9的特性,但不确定为什么在编译时会失败。

英文:

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

List&lt;String&gt; planets
    = List.of(&quot;Mercury&quot;, &quot;Venus&quot;, &quot;Earth&quot;, &quot;Mars&quot;,
    &quot;Jupiter&quot;, &quot;Saturn&quot;, &quot;Uranus&quot;, &quot;Neptune&quot;);

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

答案1

得分: 12

List.of 不是 Java 9 的特性,它是在 JDK 9 中添加的一个方法。如果你使用的是 JDK 8,它并不包含这个方法,因此无法进行编译。

简而言之,请使用更新的 JDK(同时在设置兼容级别为 9,以免创建仅能在较新 JDK 上运行的混合有效 Java 8 程序)。

英文:

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

答案2

得分: 5

一个快速的解决方法是将 List.of 替换为 JDK 8 中的 Arrays.asList

需要注意的是,这两个方法并不完全相同,List.of 返回一个不可变的列表,而 Arrays.asList 返回一个可变的列表。这里列出了一些其他的区别:

https://stackoverflow.com/questions/46579074/what-is-the-difference-between-list-of-and-arrays-aslist

英文:

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:

https://stackoverflow.com/questions/46579074/what-is-the-difference-between-list-of-and-arrays-aslist

huangapple
  • 本文由 发表于 2020年8月22日 16:51:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63534298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定