类型通配符一般是使用 " ? " 代替具体的类型实参;
所以,类型通配符是类型实参,而不是类型形参
先创建一个 Box.java 类:
public class Box {private E first;public E getFirst() {return first;}public void setFirst(E first) {this.first = first;}}
创建一个 Test.java 测试类:
showBox() 方法中的 Box<> 这里如果写 Number、Integer 的话就只能传递 Number 或者 Integer 类型,但是如果写成 ? 就表示任意类型 ->
public class Test {//Box<>这里如果写Number、Integer的话就只能传递Number或者Integer类型,但是如果写成 ? 就表示任意类型public static void showBox(Box> box) { Object first = box.getFirst();//由于 ? 表示任意类型所以这里只能用 Object 来接收System.out.println(first);}public static void main(String[] args) {Box box1 = new Box();box1.setFirst(100);showBox(box1);Box box2 = new Box();box2.setFirst(200);showBox(box2);}
}
语法 ->
类 / 接口 extends 实参类型>;
要求该泛型的类型,只能是实参类型,或实参类型的子类类型;
extends Number> 表示 Number 类型以及 Number 的子类都可以,所以是上限 ->
public class Test {public static void showBox(Box extends Number> box) { Number first = box.getFirst();//由于 "? extends Number" 表示 Number 以及 Number的子类都可,所以这里可以用 Number来接收System.out.println(first);}public static void main(String[] args) {Box box1 = new Box();box1.setFirst(100);showBox(box1);Box box2 = new Box();box2.setFirst(200);showBox(box2);}
}
语法:
类 / 接口 super 实参类型>
要求该泛型的类型,只能是实参类型,或实参类型的父类类型
super Integer > 表示 Integer 类型以及 Integer 的父类都可以,所以是下限 ->
public class Test {public static void showBox(Box super Integer> box) { Integer first = box.getFirst();//由于 "? super Integer" 表示 Integer 以及 Integer 的父类都可,所以这里可以用 Integer 来接收System.out.println(first);}public static void main(String[] args) {Box box1 = new Box();box1.setFirst(100);showBox(box1);Box box2 = new Box();box2.setFirst(200);showBox(box2);}
}
下一篇:面试官:聊聊你知道的跨域解决方案