简体   繁体   中英

Java Generics WildCard: <? extends Number> vs <T extends Number>

What is the difference between these 2 functions?

static void gPrint(List<? extends Number> l) {
    for (Number n : l) {
        System.out.println(n);
    }
}

static <T extends Number> void gPrintA(List<T> l) {
    for (Number n : l) {
        System.out.println(n);
    }
}

I see the same output.

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.

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);

T is a bounded type, ie whatever type you use, you have to stick to that particular type which extends Number , eg 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).

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM