2017-09-15 107 views
0

我有4个类。 1)Employee类 2)Nurseextends Employee 3)Doctor类也extends Employee 4)Supervisorextends Doctor如何在java中找到某个数组中某个对象的类型

内主管我有一个属性:private Employee[] arrayOfEmployees;

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

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

有人可以帮助我使用此功能?

+0

您正在寻找'instanceof'运算符。 –

+0

您可以在Employee对象上调用'getClass',它将解析它的实例类。 – Mena

回答

0

只是instanceof关键字。

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

如果您使用的Java 8,你可以使用流这个:

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

这是一个很好的解决方案,但它需要一个看起来不必要的对象创建。为什么不使用'count()'终端操作? – scottb

+0

谢谢。我有相同的想法,并已改变它。 –

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 

或使用lambda

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()); 
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(); 
    } 
} 
相关问题