/**
* 自定义泛型方法
* 泛型方法中的类型推断 和 泛型只对应引用类型的 例子
* @author lh
*/
public class GenericTest3 {
public static void main(String[] args) {
/**
* 泛型中的类型推断
* 取两个参数的类型 的 交集
* 即 3 和 5 取 整形
* 3.5 和 5 取 Number
* 3 和 abc 取 Object
*/
Integer res = add(3,5);
Number res1 = add(3.5,5);
Object res2 = add(3,"abc");
String[] array = new String[]{"a", "b", "c"};
swap(array ,1,2);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
int[] array2 = new int[] {1,2,3,4,5};
//swap(array2,3,4); //这里报错
}
/**
* 这里可以对应基本类型,是因为自动装箱
* @param x
* @param y
* @return
*/
public static <T> T add (T x, T y){
return null;
}
/**
* 泛型不能对应 基本类型 只能对应引用类型
* 这里不能进行自动装箱,是因为 new int[] 已经是一个对象了
* @param a
* @param i
* @param j
*/
private static <T> void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}