Search code examples
javagenericsbounded-wildcard

redundant declaration of methods


I want to know if there are any logical differences in declaration of these two methods:

exemple 1

public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)

exemple 2

public static <T extends Comparable<? super T>> T findMax(List<T> list)

Someone told me that this part <? extends T>is equivalent with <T> and the wildcard is redundant in first exemple, and he suggested me to use the code from the second exemple. Is that right?


Solution

  • They are not the same.

    Show this "someone" this counterproof :)

    class Scratch
    {
        interface A extends Comparable<A> {}
        interface B extends A {}
    
        public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)
        {
            return null;
        }
    
        public static <T extends Comparable<? super T>> T findMax2(List<T> list)
        {
            return null;
        }
    
        public static void main(String[] args)
        {
            List<B> listOfBs = new ArrayList<>();
    
            A foo = Scratch.<A>findMax(listOfBs);  // fine
            A bar = Scratch.<A>findMax2(listOfBs); // compiler error
        }
    }