_入门泛型的基本应用
JDK1.5新特性:泛型
1、在集合中不使用泛型操作
ArrayList collection1 = new ArrayList();
collection1.add(1); //可以添加 int 类型,编译器有警告
collection1.add(1L); //可以添加 Long 类型,编译器有警告
collection1.add("abc"); //可以添加 String类型,编译器有警告
Object obj = (Object)collection1.get(1); //不能确定得到的结果是什么类型,使用时需要强制类型转换。
2、在集合中使用泛型操作:
ArrayList<String> collection2 =new ArrayList<String>();
//collection2.add(1); //错误的代码,只能添加String类型数据。
collection2.add("abc"); //正确添加
String str = collection2.get(0); //读取数据时不需要强制类型转换。
3、在反射中应用泛型:
Constructor<String> constructor = String.class.getConstructor(StringBuffer.class);
String str = constructor.newInstance(new StringBuffer("abc")); //不需要类型转换
4、总结在哪里可以使用泛型:可以查JDK帮助文档
Class Class<T>、Class Constructor<T>、Class ArrayList<E> :凡是支持泛型的类都可以使用:<T>
_泛型的内部原理及更深应用
1、泛型对类的约束只在javac编译器进行编译时起作用,编译完成后,类字节码中不再带有泛型类型。
ArrayList<Integer> collection = new ArrayList<Integer>();
//collection.add("abc"); //错误的代码
collection.getClass().getMethod("add", Object.class).invoke(collection,"abc");
System.out.println(collection3.get(0)); //打印结果为:abc
2、泛型类型相关术语:ArrayList<E>类定义和ArrayList<Integer>类引用:
整个称为ArrayList<E> 泛型类型
ArrayList<E> 中的 E 称为 类型变量或类型参数
ArrayList<Integer> 称为 参数化的类型
ArrayList<Integer> 中的 Integer 称为类型参数的实例 或 实际类型参数
ArrayList<Integer> 中的 <> 可念成 type of
ArrayList 称为 原始类型
3、参数化类型与原始类型的兼容性:
参数化类型可以引用一个原始类型的对象,编译报警告
Collection<String> c=new vector();//可不可以就是编译器的问题。因为编译后两个类型是兼容的
原始类型可以引用一个参数化类型的对象编译报告警告
Collection c = new Vector<String>();
4、参数化类型不考虑类型的继承关系
Vector<String> v = new Vector<Object>(); //错误
Vector<Object> v = new Vector<String>(); //也是错误的
/***
Vector v1=new Vector<String>();
Vector<Object> v=v1; //这两行代码在编译的时候不会报错。***\
_泛型的通配符扩展应用
1、设计一个方法,打印任意一个泛型集合的各个元素
public void printCollection(Collection<?> collection)
{
//collection.add("abc"); //错误,在使用通配符泛型时不能调用涉及参数化类型的方法
System.out.println(collection.size()); //正确,因为size()方法不涉及参数化类型
for(Object obj : collection)
{
System.out.println(obj);
}
collection = new HashSet<Date>(); //可以这样指定引用
}
总结:使用 ? 通配符可以引用其他各种参数化的类型,? 通配符定义的变量主要用做引用,可以调用与参数化无关的方法,不能调用与参数有关的方法。
2、限定通配符的上下边界:限定通配符总是包括自己
正确:Vectot<? extends Number> x = new Vector<Integer>(); //上边界
错误:Vectot<? extends Number> x = new Vector<String>();
正确:Vectot<? super Integer> x = new Vector<Number>(); //下边界
错误:Vectot<? super Integer> x = new Vector<Byte>();
3、
Class<?> x;
Class<String> y;
x=y; //表达式正确;y=x; 表达式错误。
_泛型集合的综合应用案例
HashMap<String,Integer> maps = new HashMap<String,Integer>();
maps.put("abc",123);
maps.put("xyz",321);
Set<Map.Entry<String,Integer>> entrySet=maps.entrySet();
for(Map.Entry<String,Integer> entry:entrySet)
{
System.out.println(entry.getKey() + ":" + entry.getValue());
}
泛型入门、基本应用
猜你喜欢
转载自cdzm5211314.iteye.com/blog/2254299
今日推荐
周排行