泛型基础综合

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){
//			
//		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值