gpt4 book ai didi

java - 通用通配符类型不应在返回参数中使用

转载 作者:行者123 更新时间:2023-12-01 18:29:29 24 4
gpt4 key购买 nike

是否可以说通用通配符类型不应在方法的返回参数中使用?

换句话说,声明如下接口(interface)确实有意义:

interface Foo<T> {
Collection<? extends T> next();
}

此外,是否可以说通用通配符类型仅在方法的参数声明中才有意义?

最佳答案

使用通配符类型的主要好处(例如在方法形式参数中)是为用户提供传递的灵 active ,例如 Collection 的任何类型。 ,或List或任何实现 Collection 的东西(假设集合声明为 Collection<?> )。您经常会发现自己在形式参数中使用通配符类型。

但理想情况下,您应该避免使用它们作为方法的返回类型。因为这样,您将强制该方法的用户在调用方端使用通配符类型,即使他们不想这样做。通过使用通配符类型,您是在说,嘿!该方法可以返回任何类型的 Collection ,所以你的工作就是处理这个问题。你不应该这样做。最好使用有界类型参数。使用有界类型参数,将根据您传递的类型或方法调用的目标类型推断类型。

这里引用了Effective Java Item 28:

Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code.
Properly used, wildcard types are nearly invisible to users of a class. They cause methods to accept the parameters they should accept and reject those they should reject. If the user of a class has to think about wildcard types, there is probably something wrong with the class’s API.

关于java - 通用通配符类型不应在返回参数中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60186682/

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