下面是代码:
import java.util.*;
public class Main {
public static <T> T defaultIfNull(T object, T defaultValue) {
return object != null ? object : defaultValue;
}
public static void main(String[] args) {
List<String> ls = Collections.emptyList();
List<String> lo = defaultIfNull(ls, Collections.emptyList());
}
}使用openjdk 11,它编译得很好:
root@debian:~/tmp# java -version
openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Debian-1deb10u1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Debian-1deb10u1, mixed mode, sharing)
root@debian:~/tmp# javac ./Main.java但是,openjdk 1.8的情况并非如此
root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/java -version
openjdk version "1.8.0_41"
OpenJDK Runtime Environment (build 1.8.0_41-b04)
OpenJDK 64-Bit Server VM (build 25.40-b25, mixed mode)
root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/javac ./Main.java
./Main.java:12: error: incompatible types: inferred type does not conform to upper bound(s)
List<String> lo = defaultIfNull(ls, Collections.emptyList());
^
inferred: List<? extends Object>
upper bound(s): List<String>,Object
1 error这里的问题是,如果没有提供类型参数,Collections.emptyList将返回List<Object>。那么,是什么使openjdk 11可以做同样的事情呢?
发布于 2020-06-02 07:41:06
这是一个已在以后版本中修复的javac工具中的bug (如列出的这里)。您应该将jdk更新为更新版本,以解决此问题(并应用安全修补程序)。
此外,如果无法更新jdk版本,则可以通过指定类型来帮助编译器,如下所示:
List<String> lo = Main.<List<String>>defaultIfNull(ls, Collections.<String>emptyList());不过,我还没有测试过这个版本,因为我没有使用您的版本,但在这种情况下它可能会起作用。
https://stackoverflow.com/questions/62146849
复制相似问题