泛型的通配符,上限,下限以及泛型嵌套

来源:互联网 发布:金角大王异步网络框架 编辑:程序博客网 时间:2024/05/14 17:05

1.通配符

?:表示类型不确定,只能用于声明变量或者形参上,不能用在创建泛型类,泛型方法和接口上

public static void main(String[] args) {List<?> list=new ArrayList<Integer>();list=new ArrayList<String>();test(list);}public static void test(List<?> list){}

2.上限

extends :泛型的上限,<=(即子类或自身)

首先给出一个继承链: 

         Fruit

         /     \

   Apple  pear

class Fruit{}class Apple extends Fruit{}


然后就可以测试extends,注意这里的泛型必须为Fruit类或者它的子类

public static void main(String[] args) {Test<Fruit> test1=new Test<Fruit>();Test<Apple> test2=new Test<Apple>();}static class Test<T extends Fruit>{}

extends和通配符?一起使用

public static void main(String[] args) {List<? extends Fruit> list1=new ArrayList<Fruit>();test(list1);List<? extends Fruit> list2=new ArrayList<Apple>();test(list2);/*出错,因为List<?>等同于List<? extends Object>List<?> list3=new ArrayList<Fruit>();test(list3);*/}public static void test(List<? extends Fruit> list){}

需要注意的是,在test方法中,不能往List中添加对象,比如我写

list.add(new Fruit());这是会报错的,为了保证向下兼容的一致性,继承链不断增加,这里不能添加对象


3.下限
super :指定的类型不能小于操作的类,>=(父类或者自身)

public static void main(String[] args) {List<? super Apple> list1=new ArrayList<Fruit>();test(list1);List<? super Fruit> list2=new ArrayList<Fruit>();test(list2);List<? super Object> list3=new ArrayList<Object>();test(list3);}public static void test(List<? super Apple> list){//不能用于添加Apple父类对象list.add(new Apple());}



4.泛型嵌套

定义两个泛型类,Myclass类的泛型就是student类,而student类的泛型是String类

class Student<T>{private T score;public T getScore(){return score;}public void setScore(T score){this.score=score;}}class MyClass<T>{private T cls;public T getCls(){return cls;}public void setCls(T cls){this.cls=cls;}}public static void main(String[] args) {Student<String> stu=new Student<String>();stu.setScore("great");//泛型嵌套MyClass<Student<String>> cls=new MyClass<Student<String>>();cls.setCls(stu);Student<String> stu2=new Student<String>();stu2=cls.getCls();System.out.println(stu2.getScore());//great}


如上就实现了泛型的嵌套,在HsahMap中对键值对进行便利的时候,也利用了泛型的嵌套

public static void main(String[] args) {Map<String,String> map=new HashMap<String,String>();map.put("a", "java300");map.put("b", "马士兵javase");Set<Entry<String,String>> entrySet=map.entrySet();for(Entry<String,String> entry:entrySet){String key=entry.getKey();String value=entry.getValue();}}


5.其他问题

第一,泛型没有多态

public static void main(String[] args) {//多态Fruit f=new Apple();//泛型多态错误//List<Fruit> list=new ArrayList<Apple>();//可以用通配符来实现List<? extends Fruit> list=new ArrayList<Apple>();}

第二,泛型没有数组

public static void main(String[] args) {Fruit[] arr=new Fruit[10];//数组加泛型后有错误//Fruit<String>[] arr=new Fruit<String>[10];}
















0 0
原创粉丝点击