我见过一种类似下面所示的方法:
protected <T extends ABC> T save( T Acd, boolean en) {
它是做什么的?在Java中,这种类型的方法声明称为什么?
这是一个泛型方法,Java中将其称为“Generics”。该声明表示T可以是任何ABC子类类型。
List<Blah>
这样的代码时,你无法确定 Blah
是一个类还是一个类型参数。 - Mark Peters有时候您需要限制传递给类型参数的类型种类。例如,一个操作数字的方法可能只想接受Number类或其子类的实例。这就是bounded type parameters(有界类型参数)的作用。
要声明有界类型参数,请列出类型参数的名称,后跟extends关键字,后跟其上限。 示例:
下面的示例说明了如何在一般情况下使用extends来表示“extends”(如类)或“implements”(如接口)。此示例为通用方法,返回三个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中的泛型,您可以在这里找到更多信息。这种类型的Java方法声明称为什么?
我还想自己添加一个问题:为什么我们需要这样的东西?
有时候,您可能希望限制可用作参数化类型中类型参数的类型。例如,操作数字的方法可能只希望接受Number或其子类的实例。这就是有界类型参数的用途 [1]。
这是一个通用的保存方法,接受参数T和布尔类型,其中T必须由ABC类进行上限绑定。 ABC类或任何子类都将被接受。
这意味着您必须发送一个ABC
对象或ABC
的子类,不允许使用其他类。此外,您的Acd
变量可以使用save
方法所在的类可见的ABC
类中的方法。
当您的T
类扩展接口时,这非常有用。例如,您正在创建一个处理对象数组排序的类,此类必须实现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!
}
}