zoukankan      html  css  js  c++  java
  • java泛型<? extends E>和<? super E>的区别和适用场景

    <? extends E>是Upper Bound(上限)的通配符,用来限制元素类型的上限,如:

    List<? extends Fruit> fruits;

    表示集合中的元素的上限是Fruit类型,即只能是Fruit或者Fruit的子类,如:

    fruits = new ArrayList<Fruits>();

    fruits = new ArrayList<Apple>();

    都是合理的,但是如果是Fruit的父类就会报错,如:

    fruits = new ArrayList<Object>();

    编译会报错。

    1.写入

    fruits.add(new Apple());报错

    因为集合fruits中装的元素类型为Fruit或Fruit子类,直觉告诉我们,往fruits中添加一个Fruit类型对象或其子类对象是可行的,结果是编译都不通过,为什么?因为<? extends Fruit>只是告诉编译器集合中元素的类型上限,但它具体是什么类型编译器是不知道的,fruits可以指向ArrayList<Fruit>,也可以指向ArrayList<Apple>、ArrayList<Banana>,也就是说它的类型是不确定的,既然是不确定的,为了类型安全,编译器只能阻止添加元素了。举个例子,当你添加一个Apple时,但fruits此时指向ArrayList<Banana>,显然类型就不兼容了。当然null除外,因为它可以表示任何类型
    2.读取

    Fruit fruit = fruits.get(0);

    无论fruits指向什么,编译器都可以确定获取的元素是Fruit类型,所有读取集合中的元素是允许的

    <? super E>是 Lower Bound(下限) 的通配符 ,用来限制元素的类型下限,比如

    List<? super Apple> apples;

    表示集合中元素类型下限为Apple类型,即只能是Apple或Apple的父类,因此对于下面的赋值是合理的

    apples = new ArrayList<Apple>();

    如果元素是apple的子类,则编译不通过

    apple = new ArrayList<RedApple>();报错
    ————————————————
    版权声明:本文为CSDN博主「曾阿牛_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_35923521/article/details/77717308

  • 相关阅读:
    [Windows Azure] Windows Azure Web Sites, Cloud Services, and VMs: When to use which?
    [Windows Azure] Windows Azure Execution Models
    [Windows Azure] Load Testing in Windows Azure
    [Windows Azure]The Autoscaling Application Block
    [Windows Azure]Windows Azure Identity
    [Windows Azure] Data Management and Business Analytics
    alienware Win8 系统安装
    Navisworks Addin 插件集成
    Navisworks 2014 Api 简单的使用
    Winform简单调用WebApi
  • 原文地址:https://www.cnblogs.com/wxdlut/p/15549796.html
Copyright © 2011-2022 走看看