编译时出现Java Generics错误

时间:2011-08-25 06:33:13

标签: java generics

实施例

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您需要将sortProducts声明为:

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

这允许比较者比较T或T的任何超类。换句话说,该方法将接受Comparator<T>Comparator<A>