以这种方式将子类转换为父类是否有意义?

时间:2017-06-07 16:32:19

标签: java inheritance

class Student{
}

class CollegeStudent extends Student{
}

我有一个CollegeStudent列表,我想将其转换为Student列表:

List<CollegeStudent> collegeStudents = getStudents();
List<Student> students = new ArrayList<Student>();
for(CollegeStudent s : collegeStudents){
     students.add(s);
}

这是达到目的的合适方式吗?目的是否合理?我想要这样做的原因是我需要创建另一个类,它将Student列表作为参数,而不是CollegeStduent的列表。

1 个答案:

答案 0 :(得分:5)

那很好,但有一些较短的方法:

// Using the Collection<? extends E> constructor:
List<Student> studentsA = new ArrayList<>(collegeStudents);
// Using Collections.unmodifiableList which returns
// an unmodifiable view of the List<CollegeStudent>
// as a List<Student> without copying its elements:
List<Student> studentsB = Collections.unmodifiableList(collegeStudents);
// Older versions of Java might require a type
// witness for Collections.unmodifiableList:
List<Student> studentsC = Collections.<Student>unmodifiableList(collegeStudents);