在arraylist中实现继承

时间:2015-08-13 14:22:57

标签: java arraylist collections

addEmployee - 此方法将Employee引用作为参数,并在检查具有相同id的员工是否不存在之后将其添加到employees列表中。如果添加成功,它将返回总员工数,否则返回-1。

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)
{
.......
}
}

1 个答案:

答案 0 :(得分: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();
}