import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GenericTest {
public static void main(String[] args) {
//定义泛型
List<? extends Object> c = new ArrayList<String>();
Collection<? super Integer> t = new ArrayList<Number>();
// c.add("s");
// t.add(1f);
// Class<String> cls = Class.forName("java.lang.String");
// Integer i = add(2, 3); //T的类型值取参数的交集
// Number j = add(2.4,2);
// Object x = add(4,"4");
String[] strs = new String[]{"aa","bb","cc","dd","ee"};
Integer[] itrs = {1,2,3,4,5,6};
strs = swapArray(strs, "cc", "ee");
itrs = swapArray(itrs, 1, 4);
//泛型必须是引用类型
// swapArray(new int[]{1,2,3,4,5}, 1, 4); error
printArray(strs);
printArray(itrs);
}
//泛型用<>定义
public static <T> T add(T a,T b){
return null;
}
//打印数组
public static <T> void printArray(T[] a){
for(int i=0;i<=a.length-1;i++){
System.out.print(a[i] + " ");
}
}
//交换数组内值
public static <T> T[] swapArray(T[] a,T x,T y){
int xIndex = -1;
int yIndex = -1;
for(int i=0;i<=a.length-1;i++){
if(a[i].equals(x)){
xIndex = i;
}
if(a[i].equals(y)){
yIndex = i;
}
}
if(xIndex!=-1 && yIndex!=-1){
T temp = a[xIndex];
a[xIndex] = a[yIndex];
a[yIndex] = temp;
}
return a;
}
//可以用泛型去表示异常,但是不能catch泛型
public static <T extends Exception> void sayHello() throws T{
// try{
//
// }catch(T t){
//
// }
}
}