I have the following example and I would like to know if there is a way to tell in which order, ascending or descending, the movie arrray gets sorted just by looking at the compareTo() method WITHOUT running the code and doing trial and error.
The movie class:
package com.company;
public class Movie implements Comparable<Movie> {
private double rating;
private String name;
private int year;
// Used to sort movies by year
public int compareTo(Movie m)
{
if (this.year == m.year) {
return 0;
}
else if (this.year > m.year) {
return 1;
}
return -1;
}
// Constructor
public Movie(String nm, double rt, int yr)
{
this.name = nm;
this.rating = rt;
this.year = yr;
}
}
The main class:
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Movie> list = new ArrayList<Movie>();
list.add(new Movie("Force Awakens", 8.3, 2015));
list.add(new Movie("Star Wars", 8.7, 1977));
list.add(new Movie("Empire Strikes Back", 8.8, 1980));
list.add(new Movie("Return of the Jedi", 8.4, 1983));
Collections.sort(list);
System.out.println("Movies after sorting : ");
for (Movie movie: list)
{
System.out.println(movie.getName() + " " +
movie.getRating() + " " +
movie.getYear());
}
}
}
Result:
Movies after sorting :
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983
Force Awakens 8.3 2015