Question

Suppose we have 2 different lists.

List 1 can take any Number argument (that includes int, double, float, and everything else that is a subclass of Number).

 List<Number> l1 = new ArrayList();

So doing this works perfectly fine.

    l1.add(123);
    l1.add(123.3456);

List 2 extends Number. The problem is that I can't add anything to it and I do not understand why. Also, why would I ever need a list that < ? extends Something > instead of just creating a list of the class highest in the hierarchy that can store any subclass (like list 1)?

List<? extends Number> l2 = new ArrayList();
    l2.add(123); //Error, although Integer is a subclass of Number
    l2.add(new Integer(123)); // Wrappers don't work either
    l2.add(123.456); //Error again
Was it helpful?

Solution

The problem with calling a method such as add that has a generic parameter on a class with a ? extends wildcard is that the exact type is unknown to the compiler. It could be a List<Number> or a List<Integer> or a List<Double> or a List<BigInteger>. The compiler must preserve type safety with generics, and if it were to allow such a call, type safety would not be preserved. You shouldn't be allowed to add a Double to a list that could be a List<Integer>.

Such ? extends upper-bound wildcards are useful as method parameters themselves, where the exact type doesn't matter; it just matters that it's the bound (in this case, Number) or below.

public void foo(List<? extends Number> list) {
    for (Number n : list) {
       // do something with some kind of Number, don't care which

OTHER TIPS

? is a wildcard which is unknown to the compiler. It could be an instance of any type of class which is derived from number. Generics were implemented for the exact purpose of type safety and since the type going in is unknown, this will not work.

The wildcard is not to be used to modify a list, only to process elements already contained in the list. If you create a list or add elements to a list, you have to know which elements are exactly contained in the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top