开发者

Java Generics error while compiling

开发者 https://www.devze.com 2023-03-30 08:31 出处:网络
Example priv开发者_JS百科ate static final Comparator<A> PRODUCT_CODE_COMPARATOR = new Comparator<A>()

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>.

0

精彩评论

暂无评论...
验证码 换一张
取 消