- 当使用泛型类或者泛型接口,传递数据中,泛型的类型不确定,可以通过通配符<?>表示。一旦程序当中使用泛型的通配符后,只能使用Object类中的共性的方法,集合中元素本身方法无法使用
此时只能接收数据,不能往集合当中存储数据 - 通配符的高级使用—受限泛型(泛型的上限和下限)
- 上限:格式: 类型名称 <? extends 类名> 对象名称 意义:只能接受该类型及其子类
- 下限:格式:类型名称 <? super 类名> 对象名称 意义:只能接受该类型及其父类
public static void main(String[] args) {
Collection<Integer> list01 = new ArrayList<Integer>();
Collection<String> list02 = new ArrayList<Integer>();
Collection<Number> list03 = new ArrayList<Integer>();
Collection<Object> list04 = new ArrayList<Integer>();
}
public static void getElement(Collection<?> coll) {
pubic static void getElement(Collection<? extends Number> coll){
public static void getElement(Collection<? super Number> coll) {
- 泛型也是一种数据类型,但是不能继承
Interface extends Number extends Object 可以
List extends List extends List 不可以
public static void main(String[] args) {
Collection<Integer> list01 = new ArrayList<Integer>();
getElement(list01);
Collection<String> list02 = new ArrayList<String>();
getElement(list02);
Collection<Object> list = new ArrayList<>(String);
}
public static void getElement(Collection<Object> coll){
}