java 泛型的上限与下限
设置泛型对象的上限使用extends,表示参数类型只能是该类型或该类型的子类:
声明对象:类名<? extends 类> 对象名
定义类:类名<泛型标签 extends 类>{}
设置泛型对象的下限使用super,表示参数类型只能是该类型或该类型的父类:
声明对象:类名<? super 类> 对象名称
定义类:类名<泛型标签 extends类>{}
public static void show(List<? extends Number> l){}
public static void show(List<? super String> l){}
泛型的上限
public static void main(String[] args) {Person<Integer> p1 = new Person<>();p1.setVal(99);Person<Double> p2 = new Person<>();p2.setVal(3.14);Person<String> p3 = new Person<>();p3.setVal("007");show(p1);//√show(p2);//√show(p3);//×
}public static void show(Person<? extends Number> p){//此处限定了Person的参数类型只能是Number或者是其子类,而String并不属于Number。System.out.println(p.getVal());}
泛型的下限
public static void main(String[] args) {Person<Integer> p1 = new Person<>();p1.setVal(99);//IntegerPerson<Double> p2 = new Person<>();p2.setVal(3.14);//DoublePerson<String> p3 = new Person<>();p3.setVal("007");//StringPerson<Object> p4 = new Person<>();p4.setVal(new Object());//Objectshow(p1);//×show(p2);//×show(p3);//√show(p4);//√}public static void show(Person<? super String> p){System.out.println(p.getVal());}
很好的例子!
package generic;
import java.util.ArrayList;
import java.util.List; public class GenericDemo3 {public static void main(String[] args) {//因为show方法是用List<?>通配符接收的,所以可以是任意类型!List<String> l1 = new ArrayList<>();//new ArrayList<String>()show(l1);List<Double> l2 = new ArrayList<>();show(l2);List<Number> l3 = new ArrayList<>();show(l3); List<Object> l4 = new ArrayList<>();show(l4);//使用up方法的话接收类型为Number或者其子类//up(l1);//错误,因为up方法接收类型为Number或者其子类,l1(String)不符合!up(l2);up(l3);//使用down方法的话接收类型为Number或者其父类//down(l2);errordown(l3);down(l4);}public static void down(List<? super Number> l){for (Object object : l) {System.out.println(object);}}public static void up(List<? extends Number> l){for (Object object : l) {System.out.println(object);}}public static void show(List<?> l){for (Object object : l) {System.out.println(object);}}}