JDK5.0之后出现的新特性:泛型
泛型这种语法机制,只在程序的编译阶段起作用,只是给编译器参考的。(运行阶段泛型没用)
优点:
集合中存储的元素类型统一了。从集合中取出的元素类型是泛型指定的类型,不需要进行大量的“向下转型”!缺点:
导致集合中存储的元素缺乏多样性
大多数业务中,集合中元素的类型还是统一的。所以这种泛型特性被大家所认可。
只是方便了一种类型 如果需要调用子类特有的方法还是需要转型的。
List<Animal> list = new ArrayList<Animal>(); //使用泛型List<Animal>之后,表示list集合中只允许存储Animal类型的数据。 //list.add("ada"); Cat cat = new Cat(); Bird bird = new Bird(); //添加对象 list.add(cat); list.add(bird); Iterator<Animal> it = list.iterator(); while (it.hasNext()){ Animal a = it.next(); a.move(); if(a instanceof Cat){ ((Cat) a).catchMouse(); }else if (a instanceof Bird){ ((Bird) a).fly(); } }用户可以自定义泛型
自定义泛型的时候,<>中的只是一个标识符,可以随便写。
java源代码中经常出现的是和
E是element首字母。 T是Type单词首字母。
public class GenericTest03<asdklfhagasldfj> { public void doSome(asdklfhagasldfj a){ System.out.println(a); } public static void main(String[] args) { GenericTest03<String> gt = new GenericTest03<>(); gt.doSome("45654"); GenericTest03<Integer> gt2 = new GenericTest03<>(); gt2.doSome(100); //gt2.doSome("asdf");//类型不匹配 MyIterator<String> mI = new MyIterator<>(); String s = mI.get(); } } class MyIterator<T> { public T get(){ return null; } }