如何在java中查找数组中某个特定对象的类型

时间:2017-09-15 13:16:36

标签: java arrays class oop inheritance

我有4节课。 1)Employee课程 2)Nurseextends Employee 3)同样Doctor extends Employee的课程 4)Supervisor <{1}}

的课程

内部主管我有一个属性:extends Doctor

基本上是一群内部为医生和护士的员工。 现在我想在Supervisor类中构建一个函数,它将返回数组中护士的数量。

我的问题是我不知道如何访问数组,因为数组类型是Employee,我找护士。

有人可以帮我这个功能吗?

4 个答案:

答案 0 :(得分:2)

如果你使用java 8,你可以使用流:

int numNurses = Arrays
    .stream(employeeArray)
    .filter(e -> e instanceof Nurse.class)
    .count();

答案 1 :(得分:0)

只需使用 instanceof 关键字。

if (arrayOfEmployees[i] instanceof Nurse) {
    Nurse nurse = (Nurse) arrayOfEmployees[i];
}

答案 2 :(得分:0)

使用java 8和流

//array of employees 3 Nurses & 2 Docs
E[] aOfE = new E[] { new N(), new N(), new N(), new D(), new D() };

Predicate<E> pred = someEmp -> N.class.isInstance(someEmp);
System.out.println(Arrays.stream(aOfE).filter(pred).count());

班级:

E=Employee, N=Nurse, D=Doctor

或使用lambdas

E[] aOfE = new E[] { new N(), new N(), new N(), new D(), new D() };


System.out.println(Arrays.stream(aOfE).filter(someEmp -> N.class.isInstance(someEmp)).count());

答案 3 :(得分:0)

public class Main {

    public static void main(String[] args) {
        Supervisor supervisor = new Supervisor();
        supervisor.arrayOfEmployees = new Employee[] {new Nurse(), new Doctor(), new Doctor(), new Nurse()};

        //will be 2
        long numberOfNurses = supervisor.numberOfNurses();

        System.out.println(numberOfNurses);
    }
}

class Employee {}

class Doctor extends Employee {}

class Nurse extends Employee {}

class Supervisor extends Doctor {
    Employee[] arrayOfEmployees;

    long numberOfNurses() {
        return Stream.of(arrayOfEmployees).filter(e -> e instanceof Nurse).count();
    }
}