Java generics: wildcards

So I'm reading generics to get familiar with these concepts again, especially when it comes to wildcards, because I hardly use them or encounter them From my reading, I can't understand why they use wildcards An example I keep coming across is as follows

void printCollection( Collection<?> c ) {
  for (Object o : c){
    System.out.println(o);
  }
}

Why don't you write this:

<T> void printCollection( Collection<T> c ) {
    for(T o : c) {
        System.out.println(o);
    }
}

Another example from Oracle website:

public static double sumOfList(List<? extends Number> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

Why isn't this written

public static <T extends Number> double sumOfList(List<T> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

Did I miss anything?

Solution

Starting with Oracle:

interface Collection<E> {
     public boolean containsAll(Collection<?> c);
     public boolean addAll(Collection<? extends E> c);
 }
interface Collection<E> {
     public <T> boolean containsAll(Collection<T> c);
     public <T extends E> boolean addAll(Collection<T> c);
     // Hey,type variables can have bounds too!
 }

So for the first example, this is because the operation is not type dependent

For the second, this is because it depends only on the number class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>