如何创建一个已经存在于另一种方法中的新对象



我有一个包括对象电影的数组movieScedule。在这个电影对象中,我有门票的价格。

现在我想创建一种显示电影最昂贵的门票的方法。

方法:

public Movie mostExpensive()
{
  ....
  ....
  ....
}

现在我正在考虑在此方法中创建新的电影对象然后循环在数组中的电影中运行然后另一个循环从整个电影中从索引0运行,并使用getMoviePrice()方法

检查每个电影价格

最后,我想声明我在此方法中创建的对象电影为最高的moviePrice然后返回(电影)

有什么想法吗?也许有更好的方法?

所以我想,您有一个电影类,例如:

class Movie {
    private Double moviePrice;
}

您想找到最高价格的任何人,而不是价格最高的电影。

Movie mostExpensive() {
    Movie mostExpensiveMovie = null;
    for (Movie movie : movieScedule) {
        if (mostExpensiveMovie == null || //use for the first element
                // compare previous film price with current one
                movie.getMoviePrice() > mostExpensiveMovie.getMoviePrice()) {
            mostExpensiveMovie = movie;
        }
    }
    return mostExpensiveMovie; // return most expensive movie
}

这将更便宜,无需创建新的电影实例。如果愿意,这也可以通过Java8流来实现,请检查此堆栈帖子。

Optional<Movie> mostExpensiveMovie = Arrays.stream(movieScedule)
        .max(Comparator.comparing(Movie::getTicketPrice));

如果您使用的是Java 8或以上,我建议利用Java流。看起来像这样:

public static Movie mostExpesive(Movie[] MoviesSchedule) {
    Optional<Movie> maxPriceMovie = Stream.of(MoviesSchedule)
            .collect(Collectors.maxBy((a, b) -> a.price - b.price));
    return maxPriceMovie.get();
}

很难理解您的问题。希望这就是您想要的。获得最昂贵的票的一种简单方法是:

ArrayList<Movie> movies = new ArrayList<>();
//populate array list
public Movie getMostExpensiveTicket(ArrayList<Movie> movies) {
    Movie mostExpensive = movies.get(0); // not null save
    for (Movie movie : movies) {
        if (movie.getMoviePrice() > mostExpensive.getMoviePrice())
            mostExpensive = movie;
    }
    return mostExpensive;
}

最新更新