是否可以编写一个方法,允许我接收属于父类 Person
的对象列表。
在Person
类下,有几个子类,其中包括Employee
类。
我希望该方法返回一个单独的列表,其中仅包含原始列表中的 Employee
对象。
谢谢
最佳答案
你需要一步一步来:
- 迭代
List<Person
检查所有这些 - 如果当前元素是 en
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。 Java-8 方式与 Streams
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
}
关于Java 从父类中获取子类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49790338/