大家观察下面代码:
public class GenericDemo { public static void main(String[] args) { Collection coll = new ArrayList(); coll.add("abc"); coll.add("itcast"); coll.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放 Iterator it = coll.iterator(); while(it.hasNext()){ //需要打印每个字符串的长度,就要把迭代出来的对象转成String类型 String str = (String) it.next();//java.lang.ClassCastException System.out.println(str.length()); } } }程序在运行时发生了问题java.lang.ClassCastException。 为什么会发生类型转换异常呢? 我们来分析下:由于集合中什么类型的元素都可以存储。导致取出时强转引发运行时 ClassCastException。 怎么来解决这个问题呢? Collection虽然可以存储各种对象,但实际上通常Collection只存储同一类型对象。例如都是存储字符串对象。因此在JDK5之后,新增了泛型(Generic)语法,让你在设计API时可以指定类或方法支持泛型,这样我们使用API的时候也变得更为简洁,并得到了编译时期的语法检查。
在创建对象的时候确定泛型
public class Generic <T>{ private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } } public class GenericDemo3 { public static void main(String[] args) { Generic<String> g1 = new Generic<String>(); g1.setT("林青霞"); System.out.println(g1.getT()); Generic<Integer> g2 = new Generic<Integer>(); g2.setT(30); System.out.println(g2.getT()); Generic<Boolean> g3 = new Generic<Boolean>(); g3.setT(true); System.out.println(g3.getT()); } }调用方法时,确定泛型的类型
public class Generic2 { public <T> void show(T t){ System.out.println(t); } } public class GenericDemo4 { public static void main(String[] args) { Generic2 g = new Generic2(); g.show("张三"); g.show(11); g.show(true); } }1、定义类时确定泛型的类型
public class MyImp1 implements MyGenericInterface<String> { @Override public void add(String e) { // 省略... } @Override public String getE() { return null; } }2、始终不确定泛型的类型,直到创建对象时,确定泛型的类型
public class MyImp2<E> implements MyGenericInterface<E> { @Override public void add(E e) { // 省略... } @Override public E getE() { return null; } } public class GenericInterface { public static void main(String[] args) { MyImp2<String> my = new MyImp2<String>(); my.add("aa"); } }类型通配符
格式: 类型名称 <?> 对象名称意义: 此类型的元素可以匹配任何类型泛型的上限:
格式: 类型名称 <? extends 类 > 对象名称意义: 只能接收该类型及其子类泛型的下限:
格式: 类型名称 <? super 类 > 对象名称意义: 只能接收该类型及其父类型比如:现已知Object类,String 类,Number类,Integer类,其中Number是Integer的父类
public static void main(String[] args) { Collection<Integer> list1 = new ArrayList<Integer>(); Collection<String> list2 = new ArrayList<String>(); Collection<Number> list3 = new ArrayList<Number>(); Collection<Object> list4 = new ArrayList<Object>(); getElement1(list1); getElement1(list2);//报错 getElement1(list3); getElement1(list4);//报错 getElement2(list1);//报错 getElement2(list2);//报错 getElement2(list3); getElement2(list4); } // 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类 public static void getElement1(Collection<? extends Number> coll){} // 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类 public static void getElement2(Collection<? super Number> coll){}【Java笔记】系列
异常处理Object类的equals()和toString()方法泛型、泛型通配符、可变参数集合(一)Collection接口、List接口及其实现类集合(二)Set接口及其实现类、Collections集合(三)Map接口及其实现类