Generics <? super A> doesn't allow superTypes of A to be added to the list

前端 未结 2 1375
一向
一向 2020-12-07 04:31

I am using wildcard and lower bound generics on list and yet compiler is throwing error.

Code:

int intStart = 0;       
Number num = new Integer(2);          


        
2条回答
  •  失恋的感觉
    2020-12-07 04:49

    With List, I should have been allowed to add any objects of type Integer or its superTypes e.g. Number or Object.

    That's incorrect. List doesn't mean a list that can hold any supertype of Integer. It means a list whose generic type may be some specific supertype of Integer. So it might actually be List, List or List. All of those list types may contain an Integer, but the same can't be said for Number. A Number might be a Double or a Long, which isn't allowed in a List.

    To make it a little more concrete, consider this snippet:

    Long longValue = 2L;
    List listOfIntegers = new ArrayList<>();
    // listOfIntegers.add(longValue);
    

    The commented line obviously shouldn't compile, and doesn't. But what if we added this:

    Number longAsNumber = longValue;
    List listOfSuper = listOfIntegers;
    listOfSuper.add(longAsNumber);
    

    This is equivalent to the snippet in your question. Should the final line compile? If it would, it would violate the generic invariant of List.


    In response to your comment, List is indeed unnecessary in your example. A more common case would be to add flexibility to a method parameter. For example, a method

    void addInt(List list) {
        list.add(1);
    }
    

    would only be able to accept List, which would be unnecessarily restrictive. Changing the parameter type to List would allow the method to accept List as well as List, either of which can contain an Integer value.

    This only works if the list is consuming the generic type in question. If the method tried to produce values from the list, it would be forced to assume they're of type Object, since we don't have a definite supertype. For more information, see What is PECS (Producer Extends Consumer Super)?

    提交回复
    热议问题