java泛型(1)


由集合说起

ArrayList collection1 = new ArrayList();
		collection1.add(1);
		collection1.add(1L);
		collection1.add("abc")

取位置1的数

int i = (Integer)collection1.get(1);

其实这上数是long类型,但你却强转成Integer类型


再从指定 指定类型的集合看一下


ArrayList<String> collection2 = new ArrayList<String>();
		//collection2.add(1);
		//collection2.add(1L);
		collection2.add("abc");
		String element = collection2.get(0);

如果你想存不是字符串的类型,就会报错了。


从反射来看一下,利用反射技术来生成一个对象

//new String(new StringBuffer("abc"));
		Constructor constructor1 = String.class.getConstructor(StringBuffer.class);
		String str2 = (String)constructor1.newInstance(/*"abc"*/new StringBuffer("abc"));
		System.out.println(str2.charAt(2));

前面这个需要强制转换,后面这个就不需要了


//new String(new StringBuffer("abc"));
		Constructor<String> constructor1 = String.class.getConstructor(StringBuffer.class);
		String str2 = constructor1.newInstance(/*"abc"*/new StringBuffer("abc"));
		System.out.println(str2.charAt(2));		


泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编辑器挡住源程序中的非法输入,编译器编译带类型说明的集合会去除“类型”信息,使程序运行效率不受影响


对于参数化的泛型类型,getClass()方法返回值和原始类型完全一样。由于编译生成的字节码会去掉泛型的类型信息,只要跳过编译器,就可以住某个泛型集合中加入 其它


类型的数据,例如,用反射得到的集合,再调用其add方法即可。


ArrayList<Integer> collection3 = new ArrayList<Integer>();
		System.out.println(collection3.getClass() == collection2.getClass());
		//collection3.add("abc");
		collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc");
		System.out.println(collection3.get(0));



ArrayList<E> 类定义和ArrayList<Integer>类引用中涉及如下术语


整个称为ArrayList<E>泛型类型


ArrayList<E>中的E称为类型变量或类型参数


整个ArrayList<Integer>称为参数化的类型


ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数


ArrayList<Integer>中的<>念着typeof


ArrayList称为原始类型







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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值