英文:
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<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
答案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
返回一个可变的列表。这里列出了一些其他的区别:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论