2017-09-15 104 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(); 
    } 
} 
相關問題