泛型
1.为什么使用泛型
ArrayList list=new ArrayList(); list.add(11); list.add(22); list.add(new Student("yfz",180)); Iterator iterator= list.iterator(); while(iterator.hasNext()) { Object c=iterator.next(); System.out.println(c); } // 无法使用他的特有行为 如length // 泛型为伪泛型 // 泛型擦掉 在java文件中存在 class无 //ArrayList<char>A=new ArrayList<char>(); //泛型不可以写基本数据类型 如integer,可以传入子类 //默认为Object
2. 泛型类
public class Mylist<E>{ private T t; public void set(T t){this.t=t;} public T get()return t; } //main Mylist<Integer>list=new Mylist(); //要规定类型
3. 泛型方法
public static <T> T show(T a){ return T; } public static<E> void show1(E...e) {//可变参数 for (E element : e) { System.out.println(element); } }
4. 泛型接口
-
-
实现类给出具体的类型
-
public class imp implements List<String>{ ... } main imp i =new imp();
-
-
实现类实现了一个泛型的接口
public class MyArraylist<E>implements list<E> { ... } main: MyArraylist mylist=new MyArraylist();
-
5. 泛型涉及的符号
-
背景:
static class YE{}; static class Fu extends YE{}; static class wu extends Fu{}; public static void method (ArrayList<YE>list){ }
-
弊端:
ArrayList<YE> list1 = new ArrayList<>(); ArrayList<Fu> list2 = new ArrayList<>(); ArrayList<wu> list3 = new ArrayList<>(); //method(list2); //1.泛型不具有继承性
-
但是数据具有传承性
-
list1.add(new Fu());
方案 1
-
用泛型
-
public static <T> void method(Arraylist<E>list){ }
-
弊端 可以传不相关的类
方案 2
//使用 ? // ? extend E 子类 表示未知的类型,但它是 T 或 T 的某个子类型。 // ? super E 父类
如
public static void method1(ArrayList<? extends YE>list) { } public static void method2(ArrayList<? super Fu>list){ }