Java Generics WildCard: <? extends Number> vs

前端 未结 4 500
清酒与你
清酒与你 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条回答
  •  死守一世寂寞
    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 getElement(List 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);
    

提交回复
热议问题