List中使用继承关系泛型 实战

本文介绍了在Java编程中遇到的处理继承关系泛型的场景,通过实例展示了如何在List中使用继承关系泛型。文章讨论了在尝试遍历子类对象集合时遇到的编译错误,并解释了错误原因——未正确使用泛型有界类型。通过引入“? extends”关键字,解决了方法参数类型不匹配的问题,强调了这一小知识点在实际开发中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发中,你有没有遇到过这样的情况:定义了一个抽象类/接口,然后对其子类的集合进行循环操作?有没有遇到这个循环操作需要在另一个方法内进行?有没有遇到这个循环操作需要在本方法中需要作为子类对象来使用,在另一个方法内需要当做到父类对象来用?

如果你也遇到了,那么你可能回用到如下知识 — 泛型有界类型

我们用下面的示例来描述。

学生信息抽象类

interface IStudent {
    /**
     * 获取学校编号
     * 
     * @return
     */
    String getSchoolNo();
}

sun学校的学生信息


/**
 * 太阳学校的学生
 * 
 * @author myhc
 * 
 */
public class SunStudent implements IStudent {

    String name;

    public SunStudent(String name) {
        this.name = name;
    }

    @Override
    public String getSchoolNo() {
        return "001";
    }

    public String getName() {
        return this.name;
    }
}

遍历传入sun学校学生姓名

/**
 * 遍历学生名字
 *  
 * @param students
 */
public static void traversalStudentName(List<SunStudent> students){

}

遍历传入学生的学校编号

/**
 * 遍历学校
 * 
 * @param students
 */
public static void traversalStudentSchool(List<IStudent> students){

}

调用代码示例:

/**
 * @param args
 */
 public static void main(String[] args) { 
     SunStudent student1 = new SunStudent("张三");
     SunStudent student2 = new SunStudent("李四");
     SunStudent student3 = new SunStudent("王五");

     List<SunStudent> students = new ArrayList<SunStudent>();
     students.add(student1);
     students.add(student2);
     students.add(student3);

     // 遍历学生姓名
     traversalStudentName(students);

      // 遍历学生学校
      traversalStudentSchool(students);
}

如上这么一个简单的例子,表面上看没有没问;但只要将该代码放入编辑器,不难发现,代码编译不过。
报错信息如下:

The method traversalStudentSchool(List<IStudent>) in the type Main is not applicable for the arguments 
 (List<SunStudent>)

这个不科学啊,传入的明明是对的啊,为啥会报错啊?
难道IDE出错了?
预告过改问题的人,一看就知道,哪是编译器出错啊,是我们traversalStudent方法写的有问题;
有的朋友要急眼了, NND 你忽悠我,这么简单的一个方法能有错?
其实这个方法真的没有错,错就错在我们没有考虑,用户没有传递过来一个List 对象,而传递了一个List对象;究其原因,不难错误出现在对泛型有界类型的使用上
那么如何解决呢?
更改traversalStudentSchool方法,更改结果如下:

/**
 * 遍历学校
 *   
 * @param students
 */
public static void traversalStudentSchool(List<? extends IStudent> students){

}

为什么这样就可以了呢?
这个就是泛型有界类型的运用了
其中:


“?” 代表未知类型
“extends”关键字声明了类型的上界,表示参数化的类型可能是所指定的类型,或者是此类型的子类


通过这样的描述,现在大家知道怎么写有可能传递子集合的方法了吗?

虽然知识小,但是很有用哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值