使用Double.compare方法工作正常:
public static void main(String[] args) throws IOException, ClassNotFoundException {
final List films = new ArrayList<>();
films.add(new Film().setRating(1));
films.add(new Film().setRating(2.5));
films.add(new Film().setRating(3.5));
films.add(new Film().setRating(4));
films.add(new Film().setRating(5));
films.add(new Film().setRating(1));
films.add(new Film().setRating(2));
films.add(new Film().setRating(3));
films.add(new Film().setRating(4));
System.out.println(films);
Collections.sort(films, new Comparator() {
@Override
public int compare(Film o1, Film o2) {
return Double.compare(o1.getRating(), o2.getRating());
}
});
System.out.println(films);
}
输出:
[1.0, 2.5, 3.5, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0]
[1.0, 1.0, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0, 5.0]
我用过的电影:
private static final class Film {
double rating;
public double getRating() {
return rating;
}
public Film setRating(double rating) {
this.rating = rating;
return this;
}
@Override
public String toString() {
return Double.toString(rating);
}
}
我建议使用Double.compare而不是你的版本,甚至是o1.getRating – o2.getRating.
这或者你的电影实现是错误的 – 也许你的例子中的setter没有设置任何东西?