Java泛型
泛型函数实例
package example;
public class TDemo {
public static void main(String[] args) {
Integer[] a = {2,3,4};
Double[] b = {2.0,3.0,4.0};
Float[] c = {2.0f,3.0f,4.0f};
printArr(a);
printArr(b);
printArr(c);
}
public static <T> void printArr(T[] a) {
for(T item : a) {
System.out.println(item);
}
}
}
输出
2
3
4
2.0
3.0
4.0
2.0
3.0
4.0
代码练习
package example;
public class MaxT {
public static void main(String[] args) {
System.out.println(max(2,3));
System.out.println(max(23.0,3.1));
System.out.println(max("a","b"));
}
public static <T extends Comparable<T>> T max(T t1, T t2) {
T ret = t1;
if(t1.compareTo(t2) == -1) {
ret = t2;
}
return ret;
}
}
输出:
3
23.0
b