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列表。
最佳答案
很好,但是有几种较短的方法:
// 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);