我正在使用几个比较器将对象的 ArrayList 排序为降序或升序。目前,这些比较器属于不同的类别。如何将以下比较器组合成一个类?
class ascendingSortComparator implements Comparator<Movie> { //sort movie ascending
@Override
public int compare(Movie movie1, Movie movie2) {
return movie1.getTitle().compareTo(movie2.getTitle());
}
}
class descendingSortComparator implements Comparator<Movie> { //sort movie ascending
@Override
public int compare(Movie movie1, Movie movie2) {
return -movie1.getTitle().compareTo(movie2.getTitle());
}
}
如果这是可能的,我将如何调用适当的比较器。目前我这样称呼它:
public void sortData() {
String option = (String) sortComboBox.getSelectedItem();
if ("Ascending".equals(option)) {
Collections.sort(movieCatalog, new ascendingSortComparator());
//indexCount = (movieCatalog.size()-1) - indexCount;
//displayData(indexCount);
}
if ("Descending".equals(option)) {
Collections.sort(movieCatalog, new descendingSortComparator());
//indexCount = (movieCatalog.size()-1) - indexCount;
//displayData(indexCount);
}
}