&lt ;?有什么区别?扩展对象>和< E扩展对象>? [英] What is difference between <? extends Object> and <E extends Object>?

查看:99
本文介绍了&lt ;?有什么区别?扩展对象>和< E扩展对象>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?>有什么区别? extends Object> < E extends Object>
什么时候应该使用另一个?

解决方案

以下是我立即想到的一些差异:




  • 类型参数边界可以指定多个边界 - T扩展A& B ,但通配符不能指定多个边界 - ?扩展A& B 无效。

  • 您可以使用通配符的下限 - ?超级A 是有效的,但不是类型参数 - T super A 无效。


  • 在创建泛型类型时不能使用通配符边界。你必须使用类型参数的边界。在一个方法里面,如果你想要传递参数的类型参数之间的关系,那么你必须使用类型参数界限。例如,您想要传递两个具有相同类型参数的参数化类型。你不能用通配符边界来做到这一点。因此,下面的方法声明将采用相同类型参数的两个列表,它扩展了 Number

      public< T extends Number> void merge(List< T> list1,List< T> list2){
    }




为了结束,我将添加一些来自有效Java的项目 - 项目28:使用有界通配符来增加API灵活性:




为了获得最大的灵活性,请在代表生产者或消费者的输入参数上使用通配符类型。如果一个输入参数既是一个生产者又是一个消费者,那么通配符类型对你没有好处:你需要一个确切的类型匹配,这就是没有任何通配符的情况。

不要使用通配符类型作为返回类型。它不会为您的用户提供额外的灵活性,而是会强制他们在客户端代码中使用通配符类型。正确使用时,通配符类型对于类的用户几乎不可见。它们使方法接受它们应该接受的参数并拒绝它们应该拒绝的参数。 如果某个类的用户必须考虑通配符类型,则该类的API可能有问题。




$ b Angelika Langer - JavaGenericsFAQ



What is difference between <? extends Object> and <E extends Object> ? When should one be used over the other?

解决方案

Here are some differences that immediately comes to my mind:

  • Type parameter bounds can specify multiple bounds - T extends A & B, but with wildcard you cannot specify multiple bounds - ? extends A & B is invalid.

  • You can have lower bounds with wildcard - ? super A is valid, but not with the type parameter - T super A is not valid.

  • You cannot use wildcard bounds while creating a generic type. You have to use type parameter bounds.

  • Inside a method, if you want some relation between the type parameters of arguments passed, then you have to use type parameter bounds. For e.g, you want to pass two parameterized type with same type parameter. You can't do this with wildcard bounds. So the following method declaration will take two list of same type parameter, that extends Number.

    public <T extends Number> void merge(List<T> list1, List<T> list2) {
    }
    

To end with, I'll add some points from Effective Java - Item 28: Use bounded wildcards to increase API flexibility:

For maximum flexibility, use wildcard types on input parameters that represent producers or consumers. If an input parameter is both a producer and a consumer, then wildcard types will do you no good: you need an exact type match, which is what you get without any wildcards.

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.


References:

这篇关于&lt ;?有什么区别?扩展对象&gt;和&lt; E扩展对象&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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