Search code examples
javalistmaven

Why getLast method doesn't work for List in maven?


This simple code is failing on the build stage on maven-project.

import java.util.List;

public class Test {
    public static void main(String[] args){
        List<Integer> a = List.of(1, 2, 3);
        a.getLast();
    }
}

With an error:

java: cannot find symbol
symbol:   method getLast()
location: variable a of type java.util.List<java.lang.Integer>

If I use ctrl+click on getLast I can find this method in List:

default E getLast() {
    if (this.isEmpty()) {
        throw new NoSuchElementException();
    } else {
        return this.get(this.size() - 1);
    }
}

Moreover, if I run this code without maven everything is ok.

I'm using:

Apache Maven 3.8.8

Java version: 21

Windows 11 (10.0)

Solution

  • It sounds like maven is trying to build your code with the wrong Java version. The Java version that maven uses can be set inside your project's pom.xml file. Make sure that the pom file specifies a Java version that supports the features you are using.