泛型

    xiaoxiao2025-02-03  19

    泛型: jdk1.5出现的安全机制。 好处: 1 将运行时期的问题 ClassCastException转到了编译时期。 2 避免了强制转换的麻烦。 <>:什么时候用?当操作的数据类型不确定的时候,就需要用<>确定一个具体的范围,将数据类型传入。 jdk1.7以下: 泛型技术是给编译器使用的,确保了类型的安全。在运行时,是会进行擦除。生成的class文件是不带泛型的。 擦除的原因:为了兼容类加载器 泛型的补偿:运行时会对元素进行判断,会执行一个补偿程序,使用者无需再进行强制转换。 泛型类: jdk1.5以后使用泛型类来接收类中要操作的引用型数据。 当引用型数据不确定的时候,就是用泛型类。 public class GenericDemo2 { /* public class Tool<QQ> { private QQ q; public QQ getObject() { return q; } public void setObject(QQ q) { this.q = q; } } public class Student { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } */ public static void main(String[] args) { Tool<Student> t = new Tool<Student>(); t.setObject(new Student()); Student st = t.getObject();//不用在进行强制转换 } } 将泛型定义在方法上: 返回值和参数都可以使用  例: public<W> void show(W str){ System.out.println("show"+str); } 当方法为静态时,不能访问类的泛型,如果要使用泛型,只能将泛型定义在方法上。 例: public static <Y> void print(Y str){ System.out.println("print"+str);   // 这时不能使用Tool类的QQ } 泛型接口: package com.generic.demo; interface Inter<E>{ public void show(E e); } public class InterImp implements Inter<String> {  public void show(String str){  } } class InterImp2<E> implements Inter<E>{ public void show(E e){ } } 泛型通配符: public class GenericAdvanceDemo { public static  void main(String[] args){ ArrayList<String> a = new ArrayList<String>(); a.add("abc"); a.add("abc1"); ArrayList<Integer> a1 = new ArrayList<Integer>(); a1.add(1); a1.add(2); printCollection(a); printCollection(a1); } //? 泛型类的通配符 public static void printCollection(Collection<?> o) { Iterator<?> it = o.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } 泛型的限定: ? extends E:接收E类型或者E的子类对象。上限  使用较多! ? super E 接收E类型或者E的父类型。下限 例: public static void printCollection(Collection< ? extends Person> o) { Iterator< ? extends Person> it = o.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } 将泛型限定为Person的子类。 一般存储元素使用的上限,因为这样取出的元素就是按照上限类型来运算的。不会出现安全隐患。 例: addAll(Collection<? extendsE> c) 对元素进行取出操作时可以使用下限 例: TreeSet(Comparator<? superE> comparator) 通配符缺点: 使变量使用上不再方便 无界:参数和返回值为泛型的方法,不再使用 子类限定:参数为泛型的方法不能使用 父类限定:返回值为泛型的方法不能使用 比较通配符: boolean addAll(Collection<E> c) List<Number> numList = new ArrayList<Number>(); numList.addAll(intList) // addAll(Collection<Number> c) ,传递的是List<Integer> 两边泛型不相同所以不能使用 boolean addAll(Collection<? extends E> c) List<Number> numList = new ArrayList<Number>(); numList.addAll(intList) // addAll(Collection<? extends Number> c) ,传递的是List<Integer>
    转载请注明原文地址: https://ju.6miu.com/read-1296066.html
    最新回复(0)