我有一个类Employee
,其中包含属性(String designation, String name, int employeeID, Date dob, float salary
),另一个类Hobby
具有属性(String hobbyName, String hobbyDescription
)
该计划应将员工及其业余爱好的详细信息作为输入,然后将其作为键/值对存储在地图中......我已经完成了这项工作。
现在,用户应该能够根据员工的ID删除员工的所有详细信息。
我尝试过如下。但这是错误的
public void deleteEmployee(int id, Map<Employee,Hobby> m1)
{
if(m1.containsKey((Employee.getEmployeeID())==id)) /*getEmployeeID() is the method in 'Employee' class which returns the Id of an employee*/
m1.remove(Employee);
}
答案 0 :(得分:1)
您不会在#containsKey
方法中进行比较,而是将其存储的值传递给它。
例如,如果您有Map<Integer, Employee>
,则可能会有一个101
键指向Employee
对象,其ID为101
。因此,记住这一点:
Map<Integer, Employee> map = /* your map field, from wherever */;
Employee emp = /* your employee with id 101 */;
map.put(emp.getId(), emp); //maps "101" to the Employee with ID "101"
Employee temp = map.get(emp.getId()); //We know for sure this would be the same as "emp"
temp = map.get(101); //This should also be the same object
总而言之,如果您只想检查对象是否存在是为了删除它,您可以轻松直接调用#remove
并比较返回值
if (map.remove(101) == null) { //or map.remove(emp.getId())
//previous value did not exist, or was set manually to null
} else {
//value was removed from map
}
阅读地图界面如何在Java中工作也会有很多帮助:https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
根据您的设计而不是随机地图保存数据,为什么不将爱好存储在Set
类内的Employee
中?:
public class Employee {
private final Set<Hobby> hobbies; //The employee's hobbies
//other fields/methods/etc
}