要使用Java集合框架管理Employee對(duì)象,首先需要?jiǎng)?chuàng)建一個(gè)Employee類,然后使用Java集合類(如ArrayList、HashSet等)來存儲(chǔ)和管理Employee對(duì)象。以下是一個(gè)簡(jiǎn)單的示例:
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 +
'}';
}
}
import java.util.ArrayList;
public class EmployeeManager {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
// 添加Employee對(duì)象到ArrayList中
employees.add(new Employee("張三", 30, 5000));
employees.add(new Employee("李四", 28, 6000));
employees.add(new Employee("王五", 35, 7000));
// 遍歷并打印Employee對(duì)象
for (Employee employee : employees) {
System.out.println(employee);
}
// 刪除一個(gè)Employee對(duì)象
employees.remove(1);
// 更新一個(gè)Employee對(duì)象的信息
Employee employee = employees.get(1);
employee.setSalary(8000);
// 再次遍歷并打印Employee對(duì)象
System.out.println("After updating:");
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)Employee類,然后使用ArrayList來存儲(chǔ)和管理Employee對(duì)象。我們添加了一些Employee對(duì)象,遍歷并打印它們,刪除了一個(gè)對(duì)象,更新了一個(gè)對(duì)象的信息,并再次遍歷并打印Employee對(duì)象。你可以根據(jù)需要使用其他Java集合類(如HashSet、HashMap等)來管理Employee對(duì)象。