[英]What does <T extends mean?
我见过如下所示的方法:
protected <T extends ABC> T save( T Acd, boolean en) {
它有什么作用? 这些类型的方法声明在 Java 中称为什么?
它被称为泛型方法。 这整个概念在 Java 中称为“泛型”。 该声明意味着 T 可以是 ABC 的子类的任何类型。
有界类型参数:
有时您可能希望限制允许传递给类型参数的类型的种类。 例如,对数字进行操作的方法可能只想接受 Number 或其子类的实例。 这就是有界类型参数的用途。
要声明有界类型参数,请列出类型参数的名称,后跟 extends 关键字,然后是其上限。 例子:
以下示例说明了如何在一般意义上使用 extends 来表示“扩展”(如在类中)或“实现”(如在接口中)。 此示例是返回三个 Comparable 对象中最大的一个的通用方法:
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );
System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}
protected <T extends ABC> T save( T Acd, boolean en) {
// ...
}
在这个函数中, T
出现在三个地方
<T extends ABC>
T
T Acd
基于这些,我可以回答你的问题如下
它有什么作用?
save()
是一种通用方法,它接受两个参数,其中一个参数的类型为T
并返回T
类型的值。 T
是泛型,仅限于ABC
。 T
的范围仅限于save()
。
这些类型的方法声明在 Java 中称为什么?
IMO,答案应该是bounded type parameters ,而不是generics 。 有关 Java 中的泛型的更多信息,您可以在此处找到。
还有一个我想自己补充的问题:我们为什么要这样的东西?
有时您可能想要限制可用作参数化类型中的类型参数的类型。 例如,对数字进行操作的方法可能只想接受 Number 或其子类的实例。 这就是[1]的有界类型参数。
这是一个generic
的保存方法,除了参数 T 和布尔类型,其中 T 必须是 ABC 类的上限。 ABC 类或任何子类将被接受。
这意味着您必须发送ABC
对象或ABC
的子对象,不允许其他类。 此外,您的Acd
变量可以使用ABC
类中的方法,这些方法对包含save
方法的类可见。
当您的T
类扩展接口时,这很有用。 例如,您正在创建一个处理对象数组排序的类,并且此类必须实现 tne Comparable
接口,否则将不允许使用数组:
class Class1 implements Comparable<Class1> {
//attributes, getters and setters...
int x;
//implementing the interface...
public int compareTo(Class1 c1) {
//nice implementation of compareTo
return (this.x > c1.x)? 1 : (this.x < c1.x) ? 0 : -1;
}
}
class Class2 {
int x;
}
public class Sorter<T extends Comparable<T>> {
public static void insertionSort(T[] array) {
//good implementation of insertion sort goes here...
//just to prove that you can use the methods of the Comparable interface...
array[0].compareTo(array[1]);
}
public static void main(String[] args) {
Class1[] arrC1 = new Class1[5];
Class2[] arrC2 = new Class2[5];
//fill the arrays...
insertionSort(arrC1); //good!
insertionSort(arrC2); //compiler error!
}
}
这是泛型。 具有类型限制的泛型!
这在 Java 中称为泛型。
官方解释:
简而言之,泛型使类型(类和接口)在定义类、接口和方法时成为参数。 与方法声明中使用的更熟悉的形式参数非常相似,类型参数为您提供了一种方法,可以通过不同的输入重复使用相同的代码。 区别在于形式参数的输入是值,而类型参数的输入是类型。
非正式地:
像 Java 这样的强类型语言会导致更多错误出现在编译时而不是运行时。 这是一件好事。 但它会导致代码重复。 为了缓解这种情况,将泛型添加到 Java 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.