有界类型参数(T扩展)和上界通配符(?扩展)之间的差异 [英] Difference between Bounded Type parameter (T extends) and Upper Bound Wildcard (? extends)

查看:124
本文介绍了有界类型参数(T扩展)和上界通配符(?扩展)之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经发布了一个类似的问题,尽管我认为我的有所不同...

I know that there was a similar question already posted, although I think mine is somewhat different...

假设您有两种方法:

// Bounded type parameter
private static <T extends Number> void processList(List<T> someList) {

}

// Upper bound wildcard
private static void processList2(List<? extends Number> someList) {
    // ...
}

据我所知,两者方法接受参数,即类型为 Number List List > 编号

As far as I know, both methods accepts arguments, that are List of type Number or List of subtype of Number.

但这两种方法到底有什么区别?

But what's the difference between the two methods after all?

推荐答案

在编译期间,两种语法之间存在一些差异:

There are several differences between the two syntaxes during compile time :


  • 使用第一种语法,可以将元素添加到 someList 中,但是使用第二种语法则不能。这通常称为 PECS ,而鲜为人知的是PUT和GET prinicple。

  • 使用第一种语法,您可以使用类型参数 T 的句柄,因此您可以使用它执行类似的操作在类型 T 的方法中定义局部变量,对类型 T 的引用进行强制转换,调用可用的方法在由 T 表示的类中,等等。但是使用第二种语法,您没有类型的句柄,因此您无法执行任何操作。

  • 实际上可以从第二种方法调用第一种方法,以
    捕获通配符。这是通过助手方法捕获
    通配符的最常见方法

  • With the first syntax, you can add elements to someList but with the second, you can't. This is commonly known as PECS and less commonly known as the PUT and GET prinicple.
  • With the first syntax, you have a handle to the type parameter T so you can use it to do things such as define local variables within the method of type T, cast a reference to the type T, call methods that are available in the class represented by T, etc. But with the second syntax, you don't have a handle to the type so you can't do any of this.
  • The first method can actually be called from the second method to capture the wildcard. This is the most common way to capture a wildcard via a helper method.

private static <T extends Number> void processList(List<T> someList) {
    T n = someList.get(0);
    someList.add(1,n); //addition allowed.   
}

private static void processList2(List<? extends Number> someList) {
    Number n = someList.get(0);
    //someList.add(1,n);//Compilation error. Addition not allowed.
    processList(someList);//Helper method for capturing the wildcard
}


请注意,由于泛型是编译时的糖,因此这些更广泛的区别仅限于编译。

Note that since generics are compile time sugar, these differences at a broader level are only limited to the compilation.

这篇关于有界类型参数(T扩展)和上界通配符(?扩展)之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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