我有下面的示例,我想知道是否有一种方法可以仅通过查看compareTo()方法而无需运行代码并进行试验就可以判断电影的排列顺序是升序还是降序和错误。
电影课:
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;
}
}
主要类别:
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());
}
}
}
结果:
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