2017-06-07 36 views
2
class Student{ 
} 

class CollegeStudent extends Student{ 
} 

我有CollegeStudent的名单,我想将其转换为学生的名单:以这种方式将子类转换为父类是否有意义?

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

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

+0

不行,你已经有学生的名单'collegeStudents'不需要做任何转换 –

+1

如果它适合你的需求,那么,你可以把你的大学生同质性列表放到可能是不同种类的学生列表中。您可以通过'new ArrayList(collegeStudents)'或者'students.addAll(collegeStudents)'更简单地添加学生。没有必要自己遍历列表。 –

+0

请参阅我的补充。 – user697911

回答

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); 
+0

我不认为B和C会编译。 – shmosel

+0

@shmosel他们会。例如,请参阅http://ideone.com/L6KA5Q。 – Radiodef

+1

啊是的,我正在查看'synchronizedList()'的签名。很好的答案。 – shmosel

相关问题