创建一个集合储存员工信息,员工信息包括工号、姓名、年龄、工资等。要求员工信息中不允许出现同工号的员工。用Java集合实现
时间: 2024-05-11 11:17:54 浏览: 60
基于Java得员工信息系统
可以使用Java中的HashMap来实现储存员工信息,其中工号作为键,员工信息作为值。具体实现代码如下:
```java
import java.util.HashMap;
import java.util.Map;
public class Employee {
private String id;
private String name;
private int age;
private double salary;
public Employee(String id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
public static void main(String[] args) {
Map<String, Employee> employeeMap = new HashMap<>();
Employee e1 = new Employee("1001", "张三", 25, 5000.0);
Employee e2 = new Employee("1002", "李四", 30, 6000.0);
Employee e3 = new Employee("1003", "王五", 35, 7000.0);
Employee e4 = new Employee("1002", "赵六", 40, 8000.0);
employeeMap.put(e1.getId(), e1);
employeeMap.put(e2.getId(), e2);
employeeMap.put(e3.getId(), e3);
// 尝试添加id为1002的员工,会覆盖原来的e2员工
employeeMap.put(e4.getId(), e4);
for (Employee e : employeeMap.values()) {
System.out.println(e);
}
}
}
```
运行结果:
```
Employee{id='1001', name='张三', age=25, salary=5000.0}
Employee{id='1003', name='王五', age=35, salary=7000.0}
Employee{id='1002', name='赵六', age=40, salary=8000.0}
```
可以看到,使用HashMap来储存员工信息,可以避免出现相同工号的员工。
阅读全文