Java泛型:通配符 [英] Java generics : wildcards

查看:54
本文介绍了Java泛型:通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在阅读泛型以重新熟悉概念,尤其是在涉及通配符的情况下,因为我很少使用通配符或碰到通配符.从我读过的书中,我无法理解为什么他们使用通配符.以下是我不断遇到的例子之一.

So I was reading up on generics to re-familiarize myself with the concepts, especially where wildcards are concerned as I hardly ever use them or come across them. From the reading I've done I can not understand why they use wildcards. One of the examples I keep coming across is the following.

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网站上的另一个示例:

Another example from the oracle website:

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 :

出现的一个问题是:什么时候应该使用通用方法,什么时候应该使用通配符类型?为了理解答案,让我们研究一下Collection库中的几种方法.

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

但是,在containsAll和addAll中,类型参数T仅使用一次.返回类型不依赖于type参数,也不依赖于该方法的任何其他参数(在这种情况下,仅存在一个参数).这就告诉我们类型参数被用于多态.它的唯一作用是允许在不同的调用站点使用各种实际的参数类型.在这种情况下,应使用通配符.通配符旨在支持灵活的子类型化,这就是我们在此要表达的内容.

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.

所以对于第一个示例,是因为操作不取决于类型.

So for the first example it's because the operation doesn't depend on the type.

第二个原因是因为它仅取决于Number类.

For the second, it's because it only depends on the Number class.

这篇关于Java泛型:通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆