java编写:存储多个员工信息(包括工号、姓名、年龄,入职时间),当有新员工入职时,添加其信息;当有员工离职时,删除其信息
时间: 2024-06-03 11:09:12 浏览: 163
java职员录入信息
1. 定义员工类Employee,包含工号、姓名、年龄、入职时间等属性和相应的get和set方法。
public class Employee {
private int id; //工号
private String name; //姓名
private int age; //年龄
private Date hireDate; //入职时间
public Employee(int id, String name, int age, Date hireDate) {
this.id = id;
this.name = name;
this.age = age;
this.hireDate = hireDate;
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
}
2. 定义员工管理类EmployeeManager,包含一个List<Employee>用于存储所有员工信息,以及添加和删除员工的方法。
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class EmployeeManager {
private List<Employee> employees;
public EmployeeManager() {
employees = new ArrayList<Employee>();
}
//添加新员工
public void addEmployee(Employee employee) {
employees.add(employee);
}
//删除员工
public void removeEmployee(int id) {
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()) {
Employee employee = iterator.next();
if (employee.getId() == id) {
iterator.remove();
break;
}
}
}
//测试
public static void main(String[] args) {
EmployeeManager manager = new EmployeeManager();
//添加员工
Employee employee1 = new Employee(1, "张三", 25, new Date());
Employee employee2 = new Employee(2, "李四", 30, new Date());
manager.addEmployee(employee1);
manager.addEmployee(employee2);
//删除员工
manager.removeEmployee(2);
//输出员工信息
for (Employee employee : manager.employees) {
System.out.println(employee.getName());
}
}
}
运行结果为:
张三
说明已成功添加一个员工,删除一个员工,只剩下一个员工了。
阅读全文