泛型通配符类型不应用于返回参数中 [英] Generic wildcard types should not be used in return parameters

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

问题描述

是否可以说通用通配符类型不应该用在方法的返回参数中?换句话说,声明一个类似于接口的接口是有意义的如下所示:

  interface Foo< T> {
收藏<?延伸T>下一个();
}

另外,可以说通用通配符类型只在方法的参数声明

解决方案

使用通配符类型的主要好处,是为用户提供灵活性来传递任何类型的集合 List 或任何实现了Collection(假设集合被声明为 Collection <?>> )。您经常会发现自己在正式参数中使用通配符类型。



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



以下是来自 Java Item 28:
$ b


不要使用通配符类型作为返回类型。 b $ b为您的用户提供了额外的灵活性,这将迫使他们在客户端代码中使用
通配符类型。

正确使用的通配符类型是
,对于类的用户几乎不可见。它们使方法接受它们应该接受的
参数,并拒绝它们应该拒绝的参数。 如果
类的用户必须考虑通配符类型,则
可能与类的API有关。



Is it feasible to say that generic wildcard types should not be used in return parameters of a method?

In other words, does make sense to declare an interface like the following:

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

Additionally, is it ok to say that generic wildcard types does make sense only at method's parameter declaration?

解决方案

The main benefit of using wildcard types, say in method formal parameter, is to provide flexibility to the user to pass, say any type of Collection, or List or anything that implements Collection (assuming that the collection is declared like Collection<?>). You would often find yourself using wildcard types in formal parameters.

But ideally you should avoid using them as return type of your method. Because that way, you would force the user of that method to use wildcard types at the caller end, even if they didn't want to. By using wildcard types, you're saying that, hey! this method can return any type of Collection, so it's your job to take care of that. You shouldn't do that. Better to use bounded type parameter. With bounded type parameter, the type will be inferred based on the type you pass, or the target type of the method invocation.

And here's a quote from 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.

这篇关于泛型通配符类型不应用于返回参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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