Java arraylist中继承的实现
addEmployee–此方法将员工引用作为参数,并在检查是否不存在具有相同id的员工后将其添加到员工列表中。如果添加成功,则返回员工总数,否则返回-1Java arraylist中继承的实现,java,arraylist,collections,Java,Arraylist,Collections,addEmployee–此方法将员工引用作为参数,并在检查是否不存在具有相同id的员工后将其添加到员工列表中。如果添加成功,则返回员工总数,否则返回-1 public class Employee { private int empId; private String name; private double basicPay; private double perksPay; public Employee() { } publ
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)
{
.......
}
}
公共类员工{
私有内部empId;
私有字符串名称;
私人双基地;
私人双人房;
公职人员()
{
}
公共雇员(int-empId,字符串名,双基本工资,双额外工资){
超级();
this.empId=empId;
this.name=名称;
this.basicPay=basicPay;
this.perksPay=perksPay;
}
public int getEmpId(){
返回empId;
}
公共无效setEmpId(int-empId){
this.empId=empId;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共双getBasicPay(){
返回基本路径;
}
公共无效回退基准(双基准){
this.basicPay=basicPay;
}
公共双倍收入{
返回珀斯佩;
}
公共空间设置津贴(双倍津贴){
this.perksPay=perksPay;
}
公共类组织扩展员工
{
ArrayList emp=新的ArrayList();
公共整数加法雇员(雇员e)
{
.......
}
}
旧的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();
}
public int addEmployee(员工e){
List-alreadyInList=emp.stream().filter(em->em.getId()==e.getId()).collect(Collectors.toList());
返回alreadyInList.isEmpty()?-1:alreadyInList.size();
}
错误是什么?问题是什么?如何检查同一id是否不存在?然后将其添加到列表中?您的答案如下。