java 泛型类使用,集合中添加不同类型数据

添加

 

ArrayList<String> a = new ArrayList<String>();
a.add("CSDN_SEU_Cavin");
Class c = a.getClass();
try{
    Method method = c.getMethod("add",Object.class);
    method.invoke(a,100);
    System.out.println("lgqname:" +a);
}catch(Exception e){
    e.printStackTrace();
}

结果

 lgqname:[CSDN_SEU_Cavin, 100]

或者

 

List list = new ArrayList();
list.add("CSDN_SEU_Cavin");
list.add(100);

 

泛型类、


public class Generic<T>{ 
    //key这个成员变量的类型为T,T的类型由外部指定  
    private T key;

    public Generic(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
        this.key = key;
    }

    public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
        return key;
    }
}

传入的实参

//泛型的类型参数只能是类类型(包括自定义类),不能是简单类型
//传入的实参类型需与泛型的类型参数类型相同,即为Integer.
Generic<Integer> genericInteger = new Generic<Integer>(123456);

//传入的实参类型需与泛型的类型参数类型相同,即为String.
Generic<String> genericString = new Generic<String>("key_vlaue");

获取实参

Log.d("泛型测试","key is " + genericInteger.getKey());
Log.d("泛型测试","key is " + genericString.getKey());

 

泛型通配符

public void showKeyValue1(Generic<?> obj){
    Log.d("泛型测试","key value is " + obj.getKey());
}

 

应用1

private void navigate(Class<?> destination) {
    Intent intent = new Intent(BaseActivity.this, destination);
    startActivity(intent);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值