你可以写一个泛型方法,该方法在调用时可以接收不同类型的参数。根据传递给泛型方法的参数类型,编译器适当地处理每一个方法调用。
下面是定义泛型方法的规则:
所有泛型方法声明都有一个类型参数声明部分(由尖括号分隔),该类型参数声明部分在方法返回类型之前(在下面例子中的)。
每一个类型参数声明部分包含一个或多个类型参数,参数间用逗号隔开。一个泛型参数,也被称为一个类型变量,是用于指定一个泛型类型名称的标识符。
类型参数能被用来声明返回值类型,并且能作为泛型方法得到的实际参数类型的占位符。
泛型方法方法体的声明和其他方法一样。注意类型参数只能代表引用型类型,不能是原始类型(像int,double,char的等)。
实例
下面的例子演示了如何使用泛型方法打印不同字符串的元素:
public class genericmethodtest
{
// 泛型方法 printarray
public static < e > void printarray( e[] inputarray )
{
// 输出数组元素
for ( e element : inputarray ){
system.out.printf( "%s ", element );
}
system.out.println();
}
public static void main( string args[] )
{
// 创建不同类型数组: integer, double 和 character
integer[] intarray = { 1, 2, 3, 4, 5 };
double[] doublearray = { 1.1, 2.2, 3.3, 4.4 };
character[] chararray = { 'h', 'e', 'l', 'l', 'o' };
system.out.println( "array integerarray contains:" );
printarray( intarray ); // 传递一个整型数组
system.out.println( "\narray doublearray contains:" );
printarray( doublearray ); // 传递一个双精度型数组
system.out.println( "\narray characterarray contains:" );
printarray( chararray ); // 传递一个字符型型数组
}
}
编译以上代码,运行结果如下所示:
array integerarray contains:
1 2 3 4 5 6
array doublearray contains:
1.1 2.2 3.3 4.4
array characterarray contains:
h e l l o
有界的类型参数:
可能有时候,你会想限制那些被允许传递到一个类型参数的类型种类范围。例如,一个操作数字的方法可能只希望接受number或者number子类的实例。这就是有界类型参数的目的。
要声明一个有界的类型参数,首先列出类型参数的名称,后跟extends关键字,最后紧跟它的上界。
实例
下面的例子演示了"extends"如何使用在一般意义上的意思"extends"(类)或者"implements"(接口)。该例子中的泛型方法返回三个可比较对象的最大值。
public class maximumtest
{
// 比较三个值并返回最大值
public static > t maximum(t x, t y, t z)
{
t max = x; // 假设x是初始最大值
if ( y.compareto( max ) > 0 ){
max = y; //y 更大
}
if ( z.compareto( max ) > 0 ){
max = z; // 现在 z 更大
}
return max; // 返回最大对象
}
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" ) );
}
}
编译以上代码,运行结果如下所示:
maximum of 3, 4 and 5 is 5
maximum of 6.6, 8.8 and 7.7 is 8.8
maximum of pear, apple and orange is pear
以上就是java高级教程:泛型方法的内容。