gpt4 book ai didi

java - 当我们将自定义类对象作为键和值传递时,如何根据键名称从 HashMap 获取值

转载 作者:行者123 更新时间:2023-12-02 04:59:29 29 4
gpt4 key购买 nike

当我们将自定义类对象作为键和值对传递时,如何根据键名称从 HashMap 中获取值。在下面的代码中,当我使用 get 方法通过使用 key 检索值时,我正在获取编译时间错误。请帮助我解决这个问题。

HashMap<Employee1, Department1> hm= new HashMap<Employee1, Department1>();
hm.put(new Employee1(0, "name1", 25, 46666), new Department1(0, "developer"));
hm.put(new Employee1(0, "name2", 50, 40000), new Department1(0, "tester"));
hm.put(new Employee1(0, "name3", 34, 3000), new Department1(0, "hr"));
hm.put(new Employee1(0, "name4",30, 26666), new Department1(0, "manager"));
hm.put(new Employee1(0, "name5",28, 15000), new Department1(0, "accountant"));

Department1 value = (Department1) hm.get(0, "name5",28, 15000);
System.out.println(value);

部门.java-

package org.task;
public class Department1 {
private int deptid;
private String deptname;

public int getDeptid() {
return deptid;
}
public String getDeptname() {
return deptname;
}

public Department1(int deptid, String deptname) {
this.deptid = deptid;
this.deptname = deptname;

}

}

Employee.java-

package org.task;
public class Employee1 {
private int id;
private String name;
private int age;
private long salary;

public int getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public long getSalary() {
return salary;
}

public Employee1(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
}

我想通过传递部门 ID 或部门名称来检索员工的所有详细信息

最佳答案

您必须重写 Employee 类的 equals 方法那么你可以使用

Employee1 testEmp =  new Employee1(0, "name5",28, 15000);
Department1 value = (Department1) hm.get(testEmp);
System.out.println(value);

关于java - 当我们将自定义类对象作为键和值传递时,如何根据键名称从 HashMap 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429154/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com