Java泛型:通配符

因此,我正在阅读泛型,以便重新熟悉这些概念,特别是在涉及通配符的情况下,因为我几乎没有使用它们或碰到它们.从我所做的阅读中我无法理解为什么他们使用通配符.我不断遇到的一个例子如下.
void printCollection( Collection<?> c ) {
  for (Object o : c){
    System.out.println(o);
  }
}

为什么你不写这个:

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

来自oracle网站的另一个例子:

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

为什么这不是写的

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

我错过了什么吗?

解决方法

Oracle开始:

One question that arises is: when should I use generic methods,and when should I use wildcard types? To understand the answer,let’s examine a few methods from the Collection libraries.

interface Collection<E> {
     public boolean containsAll(Collection<?> c);
     public boolean addAll(Collection<? extends E> c);
 }

We Could have used generic methods here instead:

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!
 }

However,in both containsAll and addAll,the type parameter T is used only once. The return type doesn’t depend on the type parameter,nor does any other argument to the method (in this case,there simply is only one argument). This tells us that the type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites. If that is the case,one should use wildcards. Wildcards are designed to support flexible subtyping,which is what we’re trying to express here.

所以对于第一个例子来说,这是因为操作不依赖于类型.

对于第二个,这是因为它只取决于Number类.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...