2014-07-03 83 views
-1

我得到這個比較不適用於參數

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"); 
    } 
} 

我忘了什麼?預先感謝我的啓發。

+2

一個'Collection'不是'List'。 –

+0

這條線是幹什麼的? '收集評價=問題.' –

+0

@Alexandre Santos,它是評級的起源,來自另一個DTO。沒什麼可擔心的 –

回答

1

A Collection默認情況下不可排序(例如,HashSet是無序的Collection)。

這就是爲什麼Collections.sort(...)需要List而不是Collection

因此,正如Sotirios Delimanolis所說,它只有在ratingsList<RatingDTO>時纔有效。

的Javadoc約List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted

+0

啊所以需要將Collection 轉換成List 。 **謝謝** –

+1

np。並感謝Sotirios Delimanolis的編輯:) –