1,泛型的声明
a)在方法中的声明:
现在访问修饰符后,返回值类型前加上<T>,其它字母亦可。
b)在类中的声明:
在类名后加<T>
练习:用泛型写一个方法,将一个数组中的元素反转过来。
public class Test {
public static void main(String[] args) {
Integer []a = {1,2,3,4,5};
String []s = {"a","b","c","d","e"};
Test t = new Test();
t.sort(a);
t.sort(s);
}
private <T> void sort(T []array){
T temp;
for (int i = 0; i < (array.length)/2; i++) {
temp = array[i];
array[i]=array[array.length-i-1];
array[array.length-i-1] = temp;
}
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
}
}
结果:
5 4 3 2 1 e d c b a