比较器不适用于参数

时间:2014-07-03 07:16:16

标签: java compare

我在此

中收到以下错误
Collection<RatingDTO> ratings = question.
RatingsComparator comparator = new RatingsComparator();
Collections.sort(ratings, comparator);

错误:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Collection<RatingDTO>, RatingsComparator)

RatingDTO

import lombok.Data;

@Data
public class RatingDTO {
    private Double value;
    private Integer weekNumber;
    private Double total = 0d;
    private int numberOfAnswers = 0;

    public void addRating(Integer rating) {
        numberOfAnswers++;
        total += rating;
        value = total / numberOfAnswers;
    }
}

RatingsComparator

public class RatingsComparator implements Comparator<RatingDTO> {
    public enum Order {
        WEEK_NUMBER, AVG_RATING, AMOUNT_OF_ANSWERS
    }

    private Order sortingBy = Order.WEEK_NUMBER;

    @Override
    public int compare(RatingDTO rating1, RatingDTO rating2) {
        switch (sortingBy) {
        case WEEK_NUMBER:
            return rating1.getWeekNumber().compareTo(rating2.getWeekNumber());
        case AVG_RATING:
            return rating1.getValue().compareTo(rating2.getValue());
        case AMOUNT_OF_ANSWERS:
            return rating1.getTotal().compareTo(rating2.getTotal());
        }
        throw new RuntimeException("Practically unreachable code, can't be thrown");
    }
}

我忘记了什么?提前致谢我,祝贺我。

1 个答案:

答案 0 :(得分:1)

默认情况下,Collection无法排序(例如,HashSet是无序的Collection)。

这就是为什么Collections.sort(...)需要List而不是Collection

因此,正如Sotirios Delimanolis所说,它仅在ratingsList<RatingDTO>时才有效。

关于List的Javadoc:

  

有序集合(也称为序列)。该界面的用户可以精确控制列表中每个元素的插入位置