We have written the following Movie
class below, and we want to be able to use the Collections.sort
method to sort an ArrayList<Movie>
. We want to sort by the title
instance variable, and we want to break ties by the year
instance variable. However, our code doesn't work, and we have no idea why.
Example
ArrayList<Movie> movies = new ArrayList<>();
movies.add(new Movie("Good Burger", 1997));
movies.add(new Movie("The Lord of the Rings: The Fellowship of the Ring", 2001));
movies.add(new Movie("Fast Five", 2011));
Collections.sort(movies);
for (Movie m : movies) {
System.out.println(m);
}
will print the following:
(Fast Five, 2011)
(Good Burger, 1997)
(The Lord of the Rings: The Fellowship of the Ring, 2001)
This is the Movie
class:
class Movie implements Comparable<Movie> {
private final String title;
private final int year;
public Movie(String t, int y) {
this.title = t;
this.year = y;
}
public String toString() {
return "(" + this.title + ", " + this.year + ")";
}
public boolean equals(Object o) {
return (o instanceof Movie) && // check if o is a Movie
this.year == ((Movie)o).year && // check years for equality
this.title.equals(((Movie)o).title); // check titles for equality
}
@Override
public int compareTo(Movie m) {
return Integer.compare(this.year, m.year);
}
}
How does one implement the Comparable
interface?