gpt4 book ai didi

java - 如何将静态变量调用到非静态方法,即我需要调用 maxId 变量来插入方法

转载 作者:行者123 更新时间:2023-12-01 18:57:52 25 4
gpt4 key购买 nike

public static List<Movie> movies;

static {
movies = new ArrayList<>();
movies.add(new Movie(1, "Fprd vs Ferrari", "Movie on Racing", "abcd", "xyz"));
movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
Movie max = Collections.max(movies, Comparator.comparingInt(Movie::getId));
int maxId = max.getId();

}
public Result insert(Http.Request request) {
JsonNode jsonNode = request.body().asJson();
if (jsonNode == null) {
return badRequest("insufficient movie information");
}
Movie movie = Json.fromJson(jsonNode, Movie.class);
movies.add(movie);
return ok(Json.toJson(movie));

}

这是插入方法。现在我想访问 maxId 变量以插入方法。任何人都可以告诉我如何清除这个以增加 id

最佳答案

你不能。这是一个局部变量。

这也不是静态方法,而是静态 block 。它在类第一次加载到内存中时执行,之后不再执行。如果您想保留该值,请将代码更改为:

private static int maxId;

static {
movies = new ArrayList<>();
movies.add(new Movie(1, "Fprd vs Ferrari", "Movie on Racing", "abcd", "xyz"));
movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
Movie max = Collections.max(movies, Comparator.comparingInt(Movie::getId));
maxId = max.getId();
}

编辑

您可以做的是将最后两行提取到实际方法(静态方法或实例方法):

public static int getMaxId() {
Movie max = Collections.max(movies, Comparator.comparingInt(Movie::getId));
return max.getId();
}

并像调用任何其他方法一样调用此方法。

关于java - 如何将静态变量调用到非静态方法,即我需要调用 maxId 变量来插入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59661080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com