簡體   English   中英

Java從父類中檢索子類對象

[英]Java Retrieve Subclass Objects from Parent Class

是否可以編寫一個方法,允許我接受屬於父類Person的對象列表。

Person類下,有幾個子類,包括Employee類。

我希望該方法返回一個單獨的List,該List僅包含原始列表中的Employee對象。

謝謝

您需要按步驟執行:

  1. 迭代List<Person來檢查所有這些
  2. 如果當前元素是Employee ,則需要將其轉換為並保留它
  3. 返回keeped 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM