Example
priv开发者_JS百科ate 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;
}
Getting an error at return sortProducts(productModels, PRODUCT_CODE_COMPARATOR);
Can anyone help?
You need your declaration of sortProducts to be:
private static <T> List<T> sortProducts(final Collection<T> t,
final Comparator<? super T> comparator)
This allows the Comparator to compare T's or any super class of T. Or, in other words, the method will accept Comparator<T>
or Comparator<A>
.
精彩评论