2015-08-13 241 views
-1

addEmployee - 此方法將檢查Employee引用作爲參數,並在檢查具有相同id的僱員是否不存在後,將其添加到僱員列表中。如果添加成功,它將返回總員工數量,否則返回-1。在arraylist中實現繼承

public class Employee { 
    private int empId; 
    private String name; 
    private double basicPay; 
    private double perksPay; 
    public Employee() 
    { 

    } 
    public Employee(int empId, String name, double basicPay, double perksPay) { 
     super(); 
     this.empId = empId; 
     this.name = name; 
     this.basicPay = basicPay; 
     this.perksPay = perksPay; 
    } 
    public int getEmpId() { 
     return empId; 
    } 
    public void setEmpId(int empId) { 
     this.empId = empId; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public double getBasicPay() { 
     return basicPay; 
    } 
    public void setBasicPay(double basicPay) { 
     this.basicPay = basicPay; 
    } 
    public double getPerksPay() { 
     return perksPay; 
    } 
    public void setPerksPay(double perksPay) { 
     this.perksPay = perksPay; 
    } 
public class Organization extends Employee 
{ 

    ArrayList<Employee> emp=new ArrayList<Employee>(); 
public int addEmployee(Employee e) 
{ 
....... 
} 
} 
+0

的,什麼是錯誤? –

+0

是什麼問題? –

+0

我如何檢查相同的ID是否不存在?然後將它們添加到列表中? –

回答

0

老的Java方法:

public int addEmployee(Employee e) { 
    for (Employee employee : emp) { 
    if (e.getId() == employee.getId()) { 
     return -1; 
    } 
    } 
    emp.add(e); 
    return emp.size(); 
} 

編輯:

的Java8方式:

public int addEmployee(Employee e) { 
    List<Employee> alreadyInList = emp.stream().filter(em -> em.getId() == e.getId()).collect(Collectors.toList()); 
    return alreadyInList.isEmpty() ? -1 : alreadyInList.size(); 
}