• 目录

Java泛型基础

阅读量: 65 编辑

Java泛型基础

Java的泛型提供了编译时类型安全检测机制,该机制在编译时就可以检测到非法的类型。

泛型的本质是参数化类型,也就是说所操作的数据类型被指定为某种类型的参数。

Java中的泛型是在编译时体现的,在生成的Java字节代码中不包含泛型中的类型信息,这个叫类型擦除。

集合泛型

比如我们要写一个List,可以指定为具体的类型。

//没有加泛型限制,可以添加任何类型
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add("hello");

//类型检查,约束为整数类型
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add("hello");//报错,只能添加整数类型

泛型可以用在变量、方法、类中

泛型方法,在该方法被调用时只接收某种类型的参数

//泛型方法
public static <T> void printBox(T t){
        System.out.println("T = " + t);
}

//泛型类
class Box<T>{
    private T item; //盒子里放 T 类型的对象
    public Box(T t){
        item = t;
    }
}

泛型通配符

<? extends T> 表示该通配符所代表的类型是T类型的子类。

<? super T> 表示该通配符所代表的类型是T类型的父类。

//水果类
class Fruit {}
class Apple extends Fruit {}

//只能放水果的盒子
class Box<Fruit>{
    private Fruit item;
    public Box(Fruit t){
        item = t;
    }
    public Box(){}
}

public static void main(String[] args) {
    //可以放水果
    Box<Fruit> b = new Box<Fruit>(new Fruit());

    //报错,因为Box中只能放Fruit,不是放Fruit的子类
    Box<Fruit> box = new Box<Apple>(new Apple());
    
    //可以通过通配符解决
    Box<? extends Fruit> appleBox = new Box<Apple>(new Apple());
    
}

尝试把 class Box 改成 Apple 泛型。

class Box<Apple>{
    private Apple item;
    public Box(Apple t){
        item = t;
    }
    public Box(){}
}

public static void main(String[] args) {
    //报错,只能放苹果,不可以放 Fruit
    Box<Apple> ab = new Box<Fruit>(new Fruit());

    //可以通过通配符 super 解决
    Box<? super Apple> ab1 = new Box<Fruit>(new Fruit());
}

  • 目录