List.getFirst() 上的编译错误:找不到符号?

roz*_*rro -3 java

您能检测到编译问题吗?它在本地编译没有任何错误。但是,当使用我无法影响的远程自动编码服务编译它时,它会失败。

[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /tmp/builds/autocode_133386/src/main/java/com/classes/ArrayRectangles.java:[76,46] cannot find symbol
  symbol:   method getFirst()
  location: variable perimeters of type java.util.List<java.lang.Double>
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.849 s
[INFO] Finished at: 2024-01-17T07:57:25Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project Classes: Compilation failure
[ERROR] /tmp/builds/autocode_133386/src/main/java/com/classes/ArrayRectangles.java:[76,46] cannot find symbol
[ERROR]   symbol:   method getFirst()
[ERROR]   location: variable perimeters of type java.util.List<java.lang.Double>
Run Code Online (Sandbox Code Playgroud)

我的代码

List<Double> perimeters = new ArrayList<>();
...
double minPerim = perimeters.getFirst(); // error is here
Run Code Online (Sandbox Code Playgroud)

pom 文件

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <java.version>11</java.version>
    <junit5.version>5.8.2</junit5.version>
</properties>
...
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
    </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

Mat*_*NNZ 9

从 JDK 21 开始,方法getFirst()已添加到接口中。List

您的代码很可能在本地编译,因为您使用的是 JDK 21,但不在服务器上编译,因为服务器使用的是旧版 JDK 的映像,其中该方法尚未声明。

解决方案:

  • (长期):将服务器升级到 JDK 21
  • (短期):替换List.getFirst()List.get(0),适当注意列表何时为空(在这种情况下,get(0)会引发出界异常,因此您需要检查第.size()一个并返回null(或抛出异常,因为当前的实现getFirst()),如果列表为空。