黑马程序员———泛型

——- android培训java培训、期待与您交流! ———-
1对于泛型的理解
1,泛型的出现将运行逝去的问题(ClassCastException 转移到编译时期)
2,泛型的出现避免了类型强制类型转换 用在编译时期的技术 ,大大提高类型的安全型,
3,泛型的表现形式用 表示<> 理解泛型 当类型不确定的时候,定义<变量>来接受制定的类型,要使用什么样的类型,就将什么样 的类型传递进来。
4,好处: 不需要对存储元素进行强制类型转换,避免安全问题。
泛型的应用:

2**重点内容**1,什么时候用使用泛型:
只要使用的类后者接口上定义了<>就使用泛型并将具体类型转入
2,什么时候使用自定义泛型类呢?
当类中操作的数据类型不确定的时候,就使用泛型类。
代码示例:
import java.util.ArrayList;
import java.util.Iterator;
public class GenericDemo {
public static void main(String[] args) {
//在定义容器时,就明确要存储的元素类型。对类型进行规范。只能存储定义类型的元素
ArrayList aw = new ArrayList();
aw .add(“abc1”);
aw .add(“xxixi”);
Iterator it = aw .iterator();
while(it.hasNext()){
String s = it.next();
System.out.println(s.length());
}
}
}
ArrayList类定义和ArrayList类引用中涉及以下术语:
1,整个称为ArrayList泛型类型。
2,ArrayList中E称为类型变量或类型参数。
3,个ArrayList称为参数化的类型。
4,ArrayList中的Integer称为类型参数的实例或实际参数类型。
5,ArrayList中的< > 念为type of。
6,ArrayList称为原始类型。
参数化类型与原始类型的兼容性:

1,参数化类型可以引用一个原始类型的对象,例如:
Collection c = new Vector();
2,原始类型可以引用一个参数化类型的对象,例如:
Collection c = new Vector();
参数化类型不考虑参数的继承关系:
3,Vector v = new Vector();错误
4,Vector v = new Vector();错误
在创建数组实例时,数组的元素不能使用参数化的类型,例如下面语句有错误:
5,Vector vectorList[] = new Vector[6];
泛型中的?通配符:
6,使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以 调用与参数化无关的方法,不能调用有关的。

泛型例题:
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import cn.itcast.day1.ReflectPoint;
public class GenericTest { public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub /*ArrayList collection1 = new ArrayList();
collection1.add(1);
collection1.add(1L);
collection1.add(“abc”);
int i = (Integer)collection1.get(1);*/
ArrayList collection2 = new ArrayList();
collection2.add(“abc”);
collection2.add(“efg”);
collection2.add(“hij”);
System.out.println(collection2.get(1));
collection2.getClass().getMethod(“add”, Object.class).invoke(collection2, 123);
System.out.println(collection2);
}

——- android培训java培训、期待与您交流! ———-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值