how to call the static variable to non static method, i.e I need to call the maxId variable to insert method

64 Views Asked by At
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));

    }

This is insert method. now I want access that maxId variable to insert method. anyone can tell me how this one will cleared to get increment the id

2

There are 2 best solutions below

4
Stultuske On

You can't. It's a local variable.

That is also not a static method, it's a static block. It is executed the first time the class is loaded in the memory, and not after that. If you want to keep that value, change your code to this:

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();
}

EDIT

What you can do is extract the last two lines to an actual method (either static or instance method):

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

and call this as you would any other method.

0
k neha On

In this method we have to write this:

public Result insert(Http.Request request) {
        JsonNode jsonNode = request.body().asJson();
        if (jsonNode == null) {
            return badRequest("insufficient movie information");
        }
        String movieName = jsonNode.get("movieName").asText();
        boolean existmovie = containName(movieName);
        Movie movie = Json.fromJson(jsonNode, Movie.class);
        int nextId = Collections.max(movies, Comparator.comparingInt(Movie::getId)).getId();
        movie.setId(++nextId);
        if (existmovie == true) {
            return badRequest("Movie Already exist");
        }
        movies.add(movie);
        return ok(Json.toJson(movie));

    }