阅读量:0
要使用Java集合框架管理Employee对象,首先需要创建一个Employee类,然后使用Java集合类(如ArrayList、HashSet等)来存储和管理Employee对象。以下是一个简单的示例:
- 创建Employee类:
public class Employee { private String name; private int age; private double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } // Getter and Setter methods 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } }
- 使用ArrayList管理Employee对象:
import java.util.ArrayList; public class EmployeeManager { public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); // 添加Employee对象到ArrayList中 employees.add(new Employee("张三", 30, 5000)); employees.add(new Employee("李四", 28, 6000)); employees.add(new Employee("王五", 35, 7000)); // 遍历并打印Employee对象 for (Employee employee : employees) { System.out.println(employee); } // 删除一个Employee对象 employees.remove(1); // 更新一个Employee对象的信息 Employee employee = employees.get(1); employee.setSalary(8000); // 再次遍历并打印Employee对象 System.out.println("After updating:"); for (Employee emp : employees) { System.out.println(emp); } } }
在这个示例中,我们创建了一个Employee类,然后使用ArrayList来存储和管理Employee对象。我们添加了一些Employee对象,遍历并打印它们,删除了一个对象,更新了一个对象的信息,并再次遍历并打印Employee对象。你可以根据需要使用其他Java集合类(如HashSet、HashMap等)来管理Employee对象。