gpt4 book ai didi

Java 泛型 : wildcards

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:02:38 28 4
gpt4 key购买 nike

所以我正在阅读泛型以重新熟悉这些概念,尤其是在涉及通配符的地方,因为我几乎从不使用它们或遇到它们。从我所做的阅读中,我无法理解他们为什么使用通配符。下面是我经常遇到的一个例子。

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 类。

关于Java 泛型 : wildcards,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15125616/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com