Java从父类检索子类对象
是否可以编写一个方法,允许我接收属于父类Java从父类检索子类对象,java,Java,是否可以编写一个方法,允许我接收属于父类Person的对象列表 在Person类下,有几个子类,包括Employee类 我希望该方法返回一个单独的列表,其中只包含原始列表中的Employee对象 谢谢您需要分步骤完成: 在列表上迭代您的意思是: List<Employee> getEmployees(List<Person> personList){ List<Employee> result = new ArrayList<Employee&g
Person
的对象列表
在Person
类下,有几个子类,包括Employee
类
我希望该方法返回一个单独的列表,其中只包含原始列表中的Employee
对象
谢谢您需要分步骤完成:
列表上迭代您的意思是:
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;
}
List getEmployees(List personList){
列表结果=新建ArrayList();
for(个人:个人列表){
如果(员工的个人实例)结果。添加((员工)个人);
}
返回结果;
}
是的,你可以,分享你的尝试,我们会告诉你你想要实现什么还不清楚。请包括一份代码草图,至少大致类似于您希望它如何工作。您的意思是要筛选列表吗
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;
}