Java 泛型

Java 泛型

概览

  • 不能写基本数据类型, 因为他们不能转为 Object
  • 传递数据可以传递其子类类型
  • 不写泛型, 默认 Object

泛型

泛型类

  • 类名后面的 <>

/**
 * 泛型集合
 * @param <T> 数据类型
 */
public class MyArrayList <T>{
    Object[] arr= new Object[10];
    int size;

    public boolean add(T t){
        arr[size] = t;
        size++;
        return true;
    }

    public T get(int index){
        return (T) arr[index];
    }

    public String toString(){
        return Arrays.toString(arr);
    }

}

泛型方法

  • 修饰符<T> returnType method()
  • 类中只有少量方法需要使用不确定的类型
public<T> T method(T t){
    return t;
}
public static<T> void addAll(ArrayList<T> arrayList,T t1,T t2){
    arrayList.add(t1);
    arrayList.add(t2);
}
public static<T> void addAll(ArrayList<T> arrayList,T...t){
    for (T t1 : t) {
        arrayList.add(t1);
    }
}

泛型接口

实现类给出类型

public class MyInterfaceFanXing implements List<String> {
}
//使用
MyInterfaceFanXing list = new MyInterfaceFanXing();

类不确定泛型

public class MyInterfaceFanXing<E> implements List<E> {
}

//使用时指定类型
MyInterfaceFanXing<String> list = new MyInterfaceFanXing();

泛型通配符

  • 泛型填什么就只能是什么

限定泛型的类型

  • 使用 ? 不限定泛型类型
public void method2(ArrayList<?> arrayList){

}
  • <? extends YeYe> 类型必须是继承 YeYe类
public void method2(ArrayList<? extends YeYe> arrayList){

}
  • <? super YeYe> 类型必须是 YeYe 的父类
public void method2(ArrayList<? super YeYe> arrayList){

}