Здесь я пытаюсь продемонстрировать, как можно отсортировать массив.Для этого я использовал Arrays.sort()
.
Обратите внимание, что класс Movie
реализует интерфейс java.lang.Comparable
.Итак, класс Movie
должен реализовывать метод Comparable
compareTo()
, который я здесь сделал.
import java.util.Arrays;
public class SortMovies
{
public static void main(String[] args)
{
Movie[] movies = new Movie[6];
movies[0] = new Movie("Movie 1", "Director 1", "Actor 1", 100.5);
movies[1] = new Movie("Movie 2", "Director 2", "Actor 2", 300.5);
movies[2] = new Movie("Movie 3", "Director 3", "Actor 3", 200.5);
movies[3] = new Movie("Movie 4", "Director 4", "Actor 4", 700.5);
movies[4] = new Movie("Movie 5", "Director 5", "Actor 5", 500.5);
movies[5] = new Movie("Movie 6", "Director 6", "Actor 6", 400.5);
// Assuming that you have built this movies array somehow
// Sort
Arrays.sort(movies);
// Print sorted array
for (Movie m : movies)
{
System.out.println(m);
}
}
}
class Movie implements Comparable<Movie>
{
private String movieName;
private String movieDirector;
private String movieActor;
private double movieEarning;
Movie(String movieName, String movieDirector, String movieActor, double movieEarning)
{
this.movieName = movieName;
this.movieDirector = movieDirector;
this.movieActor = movieActor;
this.movieEarning = movieEarning;
}
@Override
public String toString()
{
return "\n" + "Movie Name = " + movieName + "\n" + "Movie Director =" + movieDirector + "\n" + "Movie Actor = " +
movieActor + "\n" + "Movie Earning = " + movieEarning;
}
@Override
public int compareTo(Movie otherMovie)
{
if (this.movieEarning > otherMovie.movieEarning)
{
return -1;
}
else if (this.movieEarning < otherMovie.movieEarning)
{
return 1;
}
else
{
return 0;
}
}
}