黑马程序员_泛型

来源:互联网 发布:tk域名怎么解析 编辑:程序博客网 时间:2024/05/29 08:10

---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! -------------------


泛型概述

     泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会去     掉“类型”信息,使程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型完全一样。由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其它类型的数据,例如,用反射得到集合,再调用其add方法即可。


了解术语

ArrayList<E> ArrayList<Integer>

整个称为ArrayList<E>泛型类型
ArrayList<E>中的E称为类型变量或类型参数
整个ArrayList<Integer>称为参数化的类型
ArrayList<Integer>中的Integer称为类型参数的实例或实际参数类型
ArrayList<Integer>中的<>念typeof
ArrayList称为原始类型

参数化类型与原始类型的兼容性

参数化类型可以引用一个原始类型的对象,编译器警告
如:Collection<String> c = new Vector();
原始类型可以引用一个参数化类型的对象,编译器警告
如:Collection c = new Vector<String>();

参数化类型不考虑类型参数的继承关系

Vector<String> v = new Vector<Object>();    //错误
Vector<Object> v = new Vectpr <String>():    //错误

在创建数组实例时,数组的元素不能使用参数化的类型,例如,下面的语句有错误
Vector<Integer> [] v = new Vector<Integer>[10];

Vector v1 = new Vector<String>();    //正确
Vector<Object> v = v1;    //正确



    泛型:JDK1.5版本以后出现的新特性,用于解决安全问题,是一个安全机制。
    好处:
        1.将运行时期出现的ClassCastException转移到了编译时期,方便与程序员解决问题,让运行时期问题减少。
        2.避免了强制转换的麻烦

public class GenericDemo {public static void main(String[] args) {ArrayList<String> al = new ArrayList<String>();al.add("abc01");al.add("abcd02");al.add("ab03");Iterator<String> it = al.iterator();while(it.hasNext()){String s = it.next();System.out.println(s+":"+s.length());}}}


泛型使用
    格式:通过<>来定义要操作的引用数据类型
    使用:通常在集合框架中很常见。
    <>是用来接收类型的
    当时用集合时,将集合中要存储的数据类型作为参数传递到<>中即可


class LenComparator implements Comparator<String>{public int compare(String o1, String o2){int num = new Integer(o1.length()).compareTo(new Integer(o2.length()));if(num==0)return o1.compareTo(o2);return num;}}public class GenericDemo2 {public static void main(String[] args) {TreeSet<String> ts = new TreeSet<String>(new LenComparator());ts.add("a");ts.add("bc");ts.add("def");ts.add("ghij");ts.add("klmno");ts.add("aaa");Iterator<String> it = ts.iterator();while(it.hasNext()){String s = it.next();System.out.println(s);}}}



泛型类
    当类中要操作的引用数据类型不确定时,定义泛型来完成扩展

class Worker{}class Student{}class Utils<AA>//泛型类{private AA a;public void setObject(AA a){this.a = a;}public AA getObject(){return a;}}public class GenericDemo3 {public static void main(String[] args) {Utils<Worker> u = new Utils<Worker>();u.setObject(new Worker());Worker w = u.getObject();}}


泛型方法
    泛型类定义的泛型,在整个类中有效,如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有方法要操作的类型就固定了。
    为了让不同方法可以操作不同类型,而且类型还不确定,那么可以将泛型定义在方法上。

class Demo<T>//泛型定义在类上{public void show(T t){System.out.println("show:"+t);}public void print(T t){System.out.println("print:"+t);}}class Demo2//泛型定义在方法上{public <T> void show2(T t){System.out.println("show2:"+t);}public <Q> void print(Q q){System.out.println("print2:"+q);}}public class GenericDemo4 {public static void main(String[] args) {Demo<Integer> d = new Demo<Integer>();d.show(3);d.print(6);Demo2 d2 = new Demo2();d2.show2("java");d2.print(5);}}


泛型接口

interface Inter<T>{void show(T t);}class InterImpl implements Inter<String>{public void show(String t){System.out.println("show:"+t);}}class InterImpl2<T> implements Inter<T>{public void show(T t){System.out.println("show2:"+t);}}public class GenericDemo5 {public static void main(String[] args) {InterImpl i = new InterImpl();i.show("java");InterImpl2<Integer> i2 = new InterImpl2<Integer>();i2.show(8);}}


泛型限定
    ?:通配符 也可以理解为占位符
    泛型的限定:
            ? extends E :可以接收E类型或者E的子类型(上限)
            ? super E :可以接收E类型或者E的父类型(下限)

class Person{private String name;Person(String name){this.name = name;}public String getName(){return name;}}class Student extends Person{Student (String name){super(name);}}public class GenericDemo6 {public static void printColl(ArrayList<? extends Person> al){Iterator<? extends Person> it = al.iterator();while(it.hasNext()){System.out.println(it.next().getName());}}public static void main(String[] args) {ArrayList<Person> al = new ArrayList<Person>();al.add(new Person("abc01"));al.add(new Person("abc02"));al.add(new Person("abc03"));ArrayList<Student> al2 = new ArrayList<Student>();al2.add(new Student("def01"));al2.add(new Student("def02"));al2.add(new Student("def02"));printColl(al2);}}


泛型限定2

class Person{private String name;Person(String name){this.name = name;}public String getName(){return name;}public String toString(){return "person:"+name;}}class Student extends Person{Student (String name){super(name);}}class Worker extends Person{Worker(String name){super(name);}}class Comp implements Comparator<Person>{public int compare(Person p1, Person p2){return p1.getName().compareTo(p2.getName());}}public class GenericDemo7 {public static void main(String[] args) {TreeSet<Student> ts = new TreeSet<Student>(new Comp());ts.add(new Student("abc03"));ts.add(new Student("abc02"));ts.add(new Student("abc04"));ts.add(new Student("abc01"));Iterator<Student> it = ts.iterator();while(it.hasNext()){System.out.println(it.next().getName());}TreeSet<Worker> ts1 = new TreeSet<Worker>(new Comp());ts1.add(new Worker("abc--03"));ts1.add(new Worker("abc--02"));ts1.add(new Worker("abc--04"));ts1.add(new Worker("abc--01"));Iterator<Worker> it1 = ts1.iterator();while(it1.hasNext()){System.out.println(it1.next().getName());}}}


自定义泛型方法及其应用


public class GenericTest5 {public static void main(String[] args) throws Exception {String[] s = new String[]{"abc","def","xyz","opq"};for(String ss : s){System.out.println(ss);}swap(s,1,3);for(String ss : s){System.out.println(ss);}}//交换任意类型数组中的元素的位置private static <T> void swap(T[] a,int i, int j){T temp = a[i];a[i] = a[j];a[j] = temp;}}


自定义泛型方法的练习


public class GenericTest6 {public static void main(String[] args) {//autoConvertObject obj1 = "abc";String s1 = autoConvert(obj1);System.out.println(s1);Object obj2 = 123;int i1 = autoConvert(obj2);System.out.println(i1);//fillArrayString[] s = new String[]{"a","b"};fillArray(s,"xx");for(String ss : s){System.out.println(ss);}//printCollectionArrayList<Integer> a1 = new ArrayList<Integer>();a1.add(1);a1.add(2);a1.add(3);printCollection(a1);//copy1String[] s2 = new String[]{"x","y","z"};ArrayList a2 = new ArrayList();copy1(s2,a2);for(Iterator it = a2.iterator(); it.hasNext();){System.out.println(it.next());}//copy2String[] ss1 = new String[]{"o","p","q"};String[] ss2 = new String[ss1.length];copy2(ss1,ss2);for(Object obj : ss2){System.out.println(obj);}}//泛型方法,将Object类型的对象转换成其他类型private static <T> T autoConvert(Object obj){return (T)obj;}//将任意类型的数组中的所有元素填充为相应类型的某个对象private static <T> void fillArray(T[] a, T obj){for(int i=0; i<a.length; i++){a[i] = obj;}}//打印出任意参数化类型的集合中的所有元素public static <T> void printCollection(Collection<T> c){for(Object obj : c){System.out.println(obj);}}//把任意类型的数组中的数据安全地复制到相应类型的另一个集合中public static <T> void copy1(T[] t, Collection<T> c){for(int i=0; i<t.length; i++){c.add(t[i]);}}//把任意类型的数组中的数据安全地复制到相应类型的另一个数组中public static <T> void copy2(T[] t1,T[] t2){for(int i=0; i<t1.length; i++){t2[i] = t1[i];}}}


自定义泛型类的应用    通过反射获得泛型的实际参数类型

getGenericParameterTypes():按照声明顺序返回一组 Type 对象,这些对象表示此 Constructor 对象所表示的方法的形参类型。

ParameterizedType 表示参数化类型,如 Collection<String>。

getRawType():返回 Type 对象,表示声明此类型的类或接口。

getActualTypeArguments():返回表示此类型实际类型参数的 Type 对象的数组。


ReflectPoint

public class ReflectPoint {private int x;public int y;public ReflectPoint(int x, int y) {super();this.x = x;this.y = y;}}


GenericDao

public class GenericDao<E> {public void add(E x){}public E findById(int id){return null;}public E findByUserName(String name){return null;}public void delete(int id){}public void update(E obj){}public Set<E> findByConditions(String where){return null;}}

GenericTest7
public class GenericTest7 {public static void main(String[] args) throws Exception {GenericDao<ReflectPoint> dao = new GenericDao<ReflectPoint>();dao.add(new ReflectPoint(3,5));//通过反射获得泛型的实际参数类型Method applyMethod = GenericTest7.class.getMethod("applyVector", Vector.class);Type[] types = applyMethod.getGenericParameterTypes();ParameterizedType pType = (ParameterizedType)types[0];System.out.println(pType.getRawType());System.out.println(pType.getActualTypeArguments()[0]);}public static void applyVector(Vector<Date> v){}}








-----------------------ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net




0 0