泛型主要用在上一章的集合上的,为了能在编译时就发现错误。
为了大家的理解,先举个反例,(这个例子将发生ClassCastException,不要再评论说这个例子为什么错)
- public class ListErr
- {
- public static void main(String[] args)
- {
- //创建一个只想保存字符串的List集合
- List strList = new ArrayList();
- strList.add("Struts2权威指南");
- strList.add("基于J2EE的Ajax宝典");
- strList.add("轻量级J2EE企业应用实战");
- //”不小心“把一个Integer对象”丢进"了集合
- strList.add(5);
- for (int i = 0; i < strList.size() ; i++ )
- {
- //因为List里取出的全部是Object,所以必须强制类型转换
- //最后一个元素将出现ClassCastException异常
- String str = (String)strList.get(i);
- }
- }
- }
为了解决这个问题,在1.5前都采用,创建个List对象的方法,但每遇到个集合都要建个对象,eg
- class StrList
- {
- private List strList = new ArrayList();
- //定义StrList的add方法
- public boolean add(String ele)
- {
- return strList.add(ele);
- }
- //重写get方法,将get方法的返回值类型改为String类型
- public String get(int index)
- {
- return (String)strList.get(index);
- }
- public int size()
- {
- return strList.size();
- }
- }
- public class CheckType
- {
- public static void main(String[] args)
- {
- //创建一个只想保存字符串的List集合
- StrList strList = new StrList();
- strList.add("Struts2权威指南");
- strList.add("基于J2EE的Ajax宝典");
- strList.add("轻量级J2EE企业应用实战");
- //下面语句不能把Integer对象“丢进”集合中,将引起编译异常
- strList.add(5);
- System.out.println(strList);
- for (int i = 0; i < strList.size() ; i++ )
- {
- //因为StrList里元素的类型就是String类型,所以无需强制类型转换
- String str = strList.get(i);
- }
- }
- }
有了泛型就方便了,eg
- public class GenericList
- {
- public static void main(String[] args)
- {
- //创建一个只想保存字符串的List集合
- List<String> strList = new ArrayList<String>();
- strList.add("Struts2权威指南");
- strList.add("基于J2EE的Ajax宝典");
- strList.add("轻量级J2EE企业应用实战");
- //下面代码将引起编译错误
- strList.add(5);
- for (int i = 0; i < strList.size() ; i++ )
- {
- //下面代码无需强制类型转换
- String str = strList.get(i);
- }
- }
- }
使用时注意:List<String>不是List<Object>子类
特殊的泛型(带类型通配符和类型上限),eg
- public class Apple<T extends Number>
- {
- T col;
- public static void main(String[] args)
- {
- Apple<Integer> ai = new Apple<Integer>();
- Apple<Double> ad = new Apple<Double>();
- //下面代码将引起编译异常
- //因为String类型传给T形参,但String不是Number的子类型。
- Apple<String> as = new Apple<String>();
- }
- }
java泛型不支持泛型数组(List<String> aa=new ArrayList<String>[10];),因为java泛型的设计原则是没有unchecked警告就没有ClassCastExcepiton. 我建议大家遇到集合数组等的时候,自己来检验数据的类型,eg
- public class test {
- public static void main(String[] args) {
- ArrayList[] aa = new ArrayList[10];
- List<Integer> li = new ArrayList<Integer>();
- li.add(3);
- ((Object[]) aa)[1] = li;
- Object target = aa[1].get(0);
- if (target instanceof Integer) {
- Integer s = (Integer) target;
- System.out.println(s);
- }
- }
- }
由于java的泛型只是编译时做下检验,大家不要想的过于强大,他的最大作用只是增强代码的可读性,别的方面也没见多大的作用。