本文共 2739 字,大约阅读时间需要 9 分钟。
泛型(Generic)是一种强类型化编程的概念,允许在编译时确保代码的类型安全。通过泛型,可以定义类、方法和接口,使其能够处理特定类型的对象,而无需依赖运行时的类型信息。这使得代码更加灵活且安全。
泛型的本质是参数化类型,数据类型的操作对象可以被指定为一个参数。例如,List<T> 中的 T 可以是任意类型,但在编译时,T 会被替换为具体的类型,从而确保类型一致性。
ClassCastException。在 Java 中,原始的集合(如 ArrayList)没有明确的类型限制,导致类型不安全。例如:
Collection coll = new ArrayList();coll.add("mobai");coll.add("墨白");coll.add(5); 当取出元素时,无法确保其类型,从而可能引发 ClassCastException。泛型的引入解决了这一问题,允许在 API 级别定义类型约束。
通过泛型,可以定义带有类型参数的类。例如,ArrayList<E> 定义为:
class ArrayList{ public boolean add(E e) {} public E get(int index) {}}
当使用时,E 会被替换为具体类型,如 Integer:
class ArrayList{ public boolean add(Integer e) {} public Integer get(int index) {}}
泛型方法允许方法接受任意类型的参数,并进行类型检查。例如:
public class GeneralMethod { public void printClassName(Type object) { System.out.println(object.getClass().getName()); }}public class Test { public static void main(String[] args) { GeneralMethod gm = new GeneralMethod(); gm.printClassName("hello"); // 输出:java.lang.String gm.printClassName(3); // 输出:java.lang.Integer }} 泛型接口允许定义方法的参数和返回类型为任意类型。例如:
interface MyGenericInterface { void add(E e); E getE();}public class MyImpl2 implements MyGenericInterface { @Override public void add(E e) {} @Override public E getE() { return null; }}public class JavaTest { public static void main(String[] args) { MyImpl2 my = new MyImpl2 (); my.add("墨白"); }} ?通配符 ? 用于限制泛型的类型范围。例如:
List<? extends Number>:只能接收 Number 及其子类。List<? super Integer>:只能接收 Integer 及其父类。public static void getElementOne(Collection collection) {} public static void getElementTow(Collection collection) {} public class JavaTest { public static void main(String[] args) { Collection c1 = new ArrayList (); Collection c2 = new ArrayList (); Collection c3 = new ArrayList (); Collection List<? extends T>:只能接收 T 及其子类。List<? super T>:只能接收 T 及其父类。例如:
List<? extends Number>:可以接受 Integer、Double 等。List<? super Number>:只能接受 Number。通过合理使用泛型,可以显著提高代码的类型安全性和可读性。
转载地址:http://njse.baihongyu.com/