泛型的推断
@Test
public void test3(){
//类型推断时使用两个类型的最小公倍数
int x1 = add(3,4);
Number x2 = add(3.5,4);
Object obj = add(3,"abc");
}
//在返回类型前加上<T>
public <T> T add(T x,T y){
return x;
}
传入一个数组,交换其中的两项:
@Test
public void test4(){
String[] result = swap(new String[]{"abc","xyz","999"}, 1, 2);
for(String s:result){
System.out.println(s);
}
Book[] bs = swap(new Book[]{new Book("三国演义","罗贯中"),new Book("水浒传","施耐庵"),new Book("红楼梦","曹雪芹")}, 0, 2);
for(Book b:bs){
System.out.println(b.getName()+","+b.getAuthor());
}
//以下做法错误,T不可以为基本类型
//int[] arr = swap(new int[]{1,2,3},1,2);
}
//在返回类型前加上<T>
public <T> T[] swap(T[] a,int i,int j){
T temp = a[i];
a[i] = a[j];
a[j] = temp;
return a;
}
定义泛型时限定类型:
@Test
public void test4(){
String[] result = swap(new String[]{"abc","xyz","999"}, 1, 2);
for(String s:result){
System.out.println(s);
}
Book[] bs = swap(new Book[]{new Book("三国演义","罗贯中"),new Book("水浒传","施耐庵"),new Book("红楼梦","曹雪芹")}, 0, 2);
for(Book b:bs){
System.out.println(b.getName()+","+b.getAuthor());
}
//以下做法错误,T不可以为基本类型
//int[] arr = swap(new int[]{1,2,3},1,2);
}
//在返回类型前加上<T>
public <T extends Object> T[] swap(T[] a,int i,int j){
T temp = a[i];
a[i] = a[j];
a[j] = temp;
return a;
}
上面代码要求T要是Object的子类,这其实是废话,如果把Object改为Number则编译时上面的两个方法都会报错,因为String和Book类都不是Number的子类。