java泛型(类型通配符)

2022-11-02  本文已影响0人  arkliu

类型通配符的引入

看下面案例:


image.png

使用类型通配符解决上面问题

public static void showBox(Box<?> box) { //使用类型通配符
        Object first = box.getFirst();
        System.out.println(first);
    }
public static void main(String[] args) {
    Box<Number>box1 = new Box<>();
    box1.setFirst(22);
    Box.showBox(box1);
        
    Box<String>box2 = new Box<>();
    box2.setFirst("hello");
    Box.showBox(box2);
}

类型通配符的上限

类型通配符的上限语法

类/接口<? extends 实参类型>
要求该泛型的类型,只能是是实参类型,或实参类型的子类类型
// ? extends Number表示接收的类型为Number或者Number的子类
public static void showBox(Box<? extends Number> box) {
    Number first = box.getFirst();
    System.out.println(first);
}
public static void main(String[] args) {
    Box<Number>box1 = new Box<>();
    box1.setFirst(22);
    Box.showBox(box1);
    
    Box<Integer>box2 = new Box<>();
    box2.setFirst(33);
    Box.showBox(box2);
}

Animal

public class Animal {

}

Cat

public class Cat extends Animal {

}

MiniCat

public class MiniCat extends Cat {

}

Test

public class Test {

    public static void main(String[] args) {
        ArrayList<Animal>animals = new ArrayList<>();
        ArrayList<Cat>cats = new ArrayList<>();
        ArrayList<MiniCat>miniCats = new ArrayList<>();
        
//      showAnimal(animals); error
        showAnimal(cats);
        showAnimal(miniCats);
    }

    /**
     * 泛型上限通配符,传递的集合类型只能是Cat或Cat的子类类型
     */
    public static void showAnimal(ArrayList<? extends Cat> list) {
        for (int i = 0; i < list.size(); i++) {
            Cat cat = list.get(i);
            System.out.println(cat);
        }
    }
}

类型通配符下限

类型通配符下限语法

类/接口<? super 实参类型>
要求该泛型的类型,只能是实参类型,或实参类型的父类类型
/**
 * 类型通配符的下限要求,要求只能是Cat或者Cat的父类类型
 */
public static void showAnimal(List<? super Cat> list) {
    for (Object obj : list) {
        System.out.println(obj);
    }
}

ArrayList<Animal>animals = new ArrayList<>();
ArrayList<Cat>cats = new ArrayList<>();
ArrayList<MiniCat>miniCats = new ArrayList<>();

showAnimal(animals); 
showAnimal(cats);
// showAnimal(miniCats); // error
上一篇 下一篇

猜你喜欢

热点阅读