在Java中管理Employee數據,首先需要創建一個Employee類,用于存儲和管理員工的信息
public class Employee {
private int id;
private String name;
private String position;
private double salary;
public Employee(int id, String name, String position, double salary) {
this.id = id;
this.name = name;
this.position = position;
this.salary = salary;
}
// Getter and Setter methods for id, name, position, and salary
}
import java.util.ArrayList;
import java.util.List;
public class EmployeeManager {
private List<Employee> employees;
public EmployeeManager() {
employees = new ArrayList<>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void removeEmployee(int id) {
employees.removeIf(employee -> employee.getId() == id);
}
public Employee getEmployeeById(int id) {
return employees.stream().filter(employee -> employee.getId() == id).findFirst().orElse(null);
}
public List<Employee> getAllEmployees() {
return employees;
}
public void updateEmployeeSalary(int id, double newSalary) {
Employee employee = getEmployeeById(id);
if (employee != null) {
employee.setSalary(newSalary);
}
}
}
public class Main {
public static void main(String[] args) {
EmployeeManager manager = new EmployeeManager();
// 添加員工
manager.addEmployee(new Employee(1, "Alice", "Software Engineer", 80000));
manager.addEmployee(new Employee(2, "Bob", "Data Analyst", 70000));
// 獲取所有員工
List<Employee> employees = manager.getAllEmployees();
for (Employee employee : employees) {
System.out.println(employee);
}
// 通過ID獲取員工
Employee employee = manager.getEmployeeById(1);
System.out.println("Employee with ID 1: " + employee);
// 更新員工薪水
manager.updateEmployeeSalary(1, 85000);
System.out.println("Updated salary of Employee with ID 1: " + manager.getEmployeeById(1));
// 刪除員工
manager.removeEmployee(2);
System.out.println("Remaining employees: " + manager.getAllEmployees());
}
}
這個示例展示了如何使用Employee和EmployeeManager類來管理員工數據。你可以根據實際需求擴展這些類,添加更多屬性和方法。