[英]Java Retrieve Subclass Objects from Parent Class
是否可以編寫一個方法,允許我接受屬於父類Person
的對象列表。
在Person
類下,有幾個子類,包括Employee
類。
我希望該方法返回一個單獨的List,該List僅包含原始列表中的Employee
對象。
謝謝
您需要按步驟執行:
List<Person
來檢查所有這些 Employee
,則需要將其轉換為並保留它 Employee
列表 1.具有foreach-loop
經典方式
public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
List<Employee> res = new ArrayList<>();
for (Person p : list) { // 1.Iterate
if (p instanceof Employee) { // 2.Check type
res.add((Employee) p); // 3.Cast and keep it
}
}
return res;
}
2.使用Streams
Java-8方式
public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
return list.stream() // 1.Iterate
.filter(Employee.class::isInstance) // 2.Check type
.map(Employee.class::cast) // 3.Cast
.collect(Collectors.toList()); // 3.Keep them
}
你的意思是:
List<Employee> getEmployees(List<Person> personList){
List<Employee> result = new ArrayList<Employee>();
for(Person person : personList){
if(person instanceof Employee) result.add((Employee)person);
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.