-2

I was going through the some legacy code in my application and I found uses of Java generics.

Can you please tell me, what is the difference between

Class<? extends T>

and

Class<? extends ?>

I am not clear about how and when to use these generics.

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
Ravi Wadje
  • 835
  • 1
  • 9
  • 13

2 Answers2

4

Class<? extends ?> is not valid type in java.

Class<? extends T> is valid type in java.

talex
  • 15,633
  • 2
  • 24
  • 56
1

Class<? extends T> example:

Class<? extends Number> can be Class<Number>, Class<Integer>, Class<BigDecimal> etc... In other words any Class that extends Number class. That is checked in compile time!

On the other hand Class<? extends ?> can be interpreted as class of type any class which extend any class and that is a nonsense.

EDIT: You're asking for usage. Here is an example of code that uses List<? extends Number> to calculate sum and average of all numbers in the list:

public class Help {

    private static BigDecimal sum(List<? extends Number> list) {
        return list == null || list.isEmpty() ?
                BigDecimal.ZERO :
                list.stream()
                        .map(n -> new BigDecimal(n.doubleValue()))
                        .reduce(BigDecimal::add)
                        .get();
    }

    private static BigDecimal average(List<? extends Number> list) {
        return list == null || list.isEmpty() ?
                BigDecimal.ZERO :
                sum(list).divide(BigDecimal.valueOf(list.size()), MathContext.DECIMAL32);
    }

    public static void main(String[] args) {

        List<Number> numbers =
                List.of(
                        1.0D,                           /*double*/
                        2.0F,                           /*float*/
                        3L,                             /*long*/
                        new BigInteger("4"),            /*BigInteger*/
                        new AtomicInteger(5),           /*just for test*/
                        (int)'a'                        /*int*/
                );

        System.out.println("sun of " + numbers + " = " + sum(numbers));
        System.out.println("avg of " + numbers + " = " + average(numbers));
        System.out.println("sum of empty list = " + sum(List.of()));
        System.out.println("avg of empty list = " + average(List.of()));
        System.out.println("sum of null list = " + sum(null));
        System.out.println("avg of null list = " + average(null));

    }
}

I hope that you can get some basic tips from this code.

zlakad
  • 1,246
  • 1
  • 9
  • 15