Java Generics WildCard: <? extends Number> vs

前端 未结 4 486
清酒与你
清酒与你 2020-12-07 09:28

What is the difference between these 2 functions?

static void gPrint(List l) {
    for (Number n : l) {
        System.out.println(n)         


        
相关标签:
4条回答
  • When you use T you can perform all type of actions on List. But when you use you can not perform add.

    T - as same as object reference with full access
    ? - give partial access

    static void gPrint(List<? extends Number> l) {
     l.add(1); //Will give error
    for (Number n : l) {
        System.out.println(n);
    }
    
    static <T extends Number> void gPrintA(List<T> l) {
    l.add((T)1); //We can add
    for (Number n : l) {
        System.out.println(n);
    }
    
    0 讨论(0)
  • 2020-12-07 09:49

    The difference is you can't refer to T when using a wildcard.

    You aren't right now, so there is "no difference", but here's how you could use T to make a difference:

    static <T extends Number> T getElement(List<T> l) {
        for (T t : l) {
            if (some condition)
                return t;
        }
        return null;
    }
    

    This will return the same type as whatever is passed in. eg these will both compile:

    Integer x = getElement(integerList);
    Float y = getElement(floatList);
    
    0 讨论(0)
  • 2020-12-07 09:58

    T is a bounded type, i.e. whatever type you use, you have to stick to that particular type which extends Number, e.g. if you pass a Double type to a list, you cannot pass it a Short type as T is of type Double and the list is already bounded by that type. In contrast, if you use ? (wildcard), you can use "any" type that extends Number (add both Short and Double to that list).

    0 讨论(0)
  • There is no difference in this case, because T is never used again.

    The reason for declaring a T is so that you can refer to it again, thus binding two parameter types, or a return type together.

    0 讨论(0)
提交回复
热议问题