创建一个Map对象要求员工类:编号 姓名 工资 用来存储员工数据 key是员工编号 value是员工对象map要用泛型 map添加3对值 用keyset和Entryset输出
时间: 2024-05-09 10:19:41 浏览: 94
以下是Java代码实现:
```java
import java.util.*;
public class Employee {
private int id;
private String name;
private double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
public static void main(String[] args) {
Map<Integer, Employee> employeeMap = new HashMap<>();
employeeMap.put(1001, new Employee(1001, "Alice", 5000));
employeeMap.put(1002, new Employee(1002, "Bob", 6000));
employeeMap.put(1003, new Employee(1003, "Charlie", 7000));
// 使用 keySet() 方法遍历 Map
System.out.println("使用 keySet() 方法遍历 Map:");
Set<Integer> keySet = employeeMap.keySet();
for (int id : keySet) {
System.out.println(employeeMap.get(id));
}
// 使用 entrySet() 方法遍历 Map
System.out.println("使用 entrySet() 方法遍历 Map:");
Set<Map.Entry<Integer, Employee>> entrySet = employeeMap.entrySet();
for (Map.Entry<Integer, Employee> entry : entrySet) {
System.out.println(entry.getValue());
}
}
}
```
输出结果为:
```
使用 keySet() 方法遍历 Map:
Employee{id=1001, name='Alice', salary=5000.0}
Employee{id=1002, name='Bob', salary=6000.0}
Employee{id=1003, name='Charlie', salary=7000.0}
使用 entrySet() 方法遍历 Map:
Employee{id=1001, name='Alice', salary=5000.0}
Employee{id=1002, name='Bob', salary=6000.0}
Employee{id=1003, name='Charlie', salary=7000.0}
```
阅读全文