在开发中,你有没有遇到过这样的情况:定义了一个抽象类/接口,然后对其子类的集合进行循环操作?有没有遇到这个循环操作需要在另一个方法内进行?有没有遇到这个循环操作需要在本方法中需要作为子类对象来使用,在另一个方法内需要当做到父类对象来用?
如果你也遇到了,那么你可能回用到如下知识 — 泛型有界类型
我们用下面的示例来描述。
学生信息抽象类
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”关键字声明了类型的上界,表示参数化的类型可能是所指定的类型,或者是此类型的子类
通过这样的描述,现在大家知道怎么写有可能传递子集合的方法了吗?
虽然知识小,但是很有用哦!