Java 这样将子类转换为父类有意义吗?
我有一份大学生名单,我想把它转换成一份学生名单:Java 这样将子类转换为父类有意义吗?,java,inheritance,Java,Inheritance,我有一份大学生名单,我想把它转换成一份学生名单: class Student{ } class CollegeStudent extends Student{ } List collegeStudents=getStudents(); List students=new ArrayList(); 对于(大学生s:大学生){ 学生。添加(s); } 这是否达到目的的适当方式?目的合理吗?我想这样做的原因是我需要创建另一个类,该类以Student列表作为参数,而不是CollegeStduent
class Student{
}
class CollegeStudent extends Student{
}
List collegeStudents=getStudents();
List students=new ArrayList();
对于(大学生s:大学生){
学生。添加(s);
}
这是否达到目的的适当方式?目的合理吗?我想这样做的原因是我需要创建另一个类,该类以Student列表作为参数,而不是CollegeStduent列表。这很好,但有一些较短的方法:
List<CollegeStudent> collegeStudents = getStudents();
List<Student> students = new ArrayList<Student>();
for(CollegeStudent s : collegeStudents){
students.add(s);
}
//使用集合否,您在大学生中已经有一个学生列表
无需进行任何转换。如果它符合您的需要,则可以将您的同质大学生列表放入一个可能的异质学生列表中。您可以通过newarraylist(collegeStudents)
或使用students.addAll(collegeStudents)
更简单地添加学生。没有必要自己反复浏览这个列表。请看我添加的内容。“我需要创建另一个类,它将学生列表作为参数”好主意!但是我还必须定义一个实例变量“list”,我认为B和C不会编译。啊,是的,我正在查看synchronizedList()
的签名。回答不错。
// 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);