|NO.Z.00057|——————————|BigDataEnd|——|Java&集合类库.V05|——|Java.v05|泛型机制.v05|泛型通配符|使用特点|有限制通配符|使用特点|

一、泛型通配符的使用和特点
### --- [泛型通配符的使用和特点]——[有限制通配符的使用和特点]

~~~     # 通配符的使用
——>        有时候我们希望传入的类型在一个指定的范围内,此时就可以使用泛型通配符了。
——>        如:之前传入的类型要求为Integer类型,
——>        但是后来业务需要Integer的父类Number类也可以传入。
——>        泛型中有三种通配符形式:
——>            <?> 无限制通配符:表示我们可以传入任意类型的参数。
——>            <? extends E> 表示类型的上界是E,只能是E或者是E的子类。
——>            <? super E> 表示类型的下界是E,只能是E或者是E的父类。
二、编程代码
package com.yanqi.task15;

public class Animal {
}
三、编程代码
package com.yanqi.task15;

public class Dog extends Animal {
}
四、编程代码
package com.yanqi.task15;

import java.util.LinkedList;
import java.util.List;

public class GenericTest {

    public static void main(String[] args) {

        // 1.声明两个List类型的集合进行测试
        List<Animal> lt1 = new LinkedList<>();
        List<Dog> lt2 = new LinkedList<>();
        // 试图将lt2的数值赋值给lt1,也就是发生List<Dog>类型向List<Animal>类型的转换
        //lt1 = lt2;  Error: 类型之间不具备父子类关系

        System.out.println("---------------------------------------------");
        // 2.使用通配符作为泛型类型的公共父类
        List<?> lt3 = new LinkedList<>();
        lt3 = lt1; // 可以发生List<Animal>类型到List<?>类型的转换
        lt3 = lt2; // 可以发生List<Dog>类型到List<?>类型的转换

        // 向公共父类中添加元素和获取元素
        //lt3.add(new Animal()); Error: 不能存放Animal类型的对象
        //lt3.add(new Dog());    Error: 不能存放Dog类型的对象, 不支持元素的添加操作

        Object o = lt3.get(0);  // ok,支持元素的获取操作,全部当做Object类型来处理

        System.out.println("---------------------------------------------");
        // 3.使用有限制的通配符进行使用
        List<? extends Animal> lt4 = new LinkedList<>();
        // 不支持元素的添加操作
        //lt4.add(new Animal());
        //lt4.add(new Dog());
        //lt4.add(new Object());
        // 获取元素
        Animal animal = lt4.get(0);

        System.out.println("---------------------------------------------");
        List<? super Animal> lt5 = new LinkedList<>();
        lt5.add(new Animal());
        lt5.add(new Dog());
        //lt5.add(new Object());  Error: 超过了Animal类型的范围
        Object object = lt5.get(0);
    }
}

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on   yanqi_vip  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示