publicclass GenericMethodTest
{
// generic method printArray publicstatic < E > voidprintArray( E[] inputArray )
{
// Display array elements for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}
publicstaticvoidmain( String args[] )
{
// Create arrays of Integer, Double and 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 ); // pass an Integer array
System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\nArray characterArray contains:" );
printArray( charArray ); // pass a Character array
}
}
可以给类型参数加限制,例如必须是Number及其子类。
publicclass MaximumTest
{
// determines the largest of three Comparable objectspublicstatic <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
}
}
2. 泛型类
类型参数跟在类名后面。
与泛型方法一样,一个泛型类的类型参数区域可以拥有一个或者更多的由逗号分隔的类型参数。
泛型方法在使用时跟普通方法一样,没有区别;但泛型类的使用不一样,需要指定具体类型。GenericClass integerObject = new GenericClass();
publicclass Box<T> {
private T t;
publicvoidadd(T t) {
this.t = t;
}
public T get() {
return t;
}
publicstaticvoidmain(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}