2011-08-25 29 views
0

在編譯

private static final Comparator<A> PRODUCT_CODE_COMPARATOR = new Comparator<A>() 
{ 
    @Override 
    public int compare(final A o1, final A o2) 
    { 
     return o1.getCode().compareTo(o2.getCode()); 
    } 
}; 
public static <T extends A> List<T> sortProductsByCode(final Collection<T> productModels) 
{ 
    return sortProducts(productModels, PRODUCT_CODE_COMPARATOR); 
} 

private static <T> List<T> sortProducts(final Collection<T> t, final Comparator<T> comparator) 
{ 
    final List<T> variants = new ArrayList<T>(t); 
    Collections.sort(variants, comparator); 
    return variants; 
} 

獲得一個錯誤返回時sortProducts(productModels,PRODUCT_CODE_COMPARATOR)Java泛型誤差;

任何人都可以幫忙嗎?

回答

2

你需要你的sortProducts的聲明是:

private static <T> List<T> sortProducts(final Collection<T> t, 
             final Comparator<? super T> comparator) 

這使得比較來比較T公司或任何超類T的或者,換句話說,該方法將接受Comparator<T>Comparator<A>