制作用户定义的地图

时间:2012-04-15 12:47:22

标签: java

我有一个名为Employee的pojo,现在我想创建一个我想要放在地图上的用户定义集合。请告诉我如何实现这一目标。

public class Employee {
    String name,job;
    int salary;

    public Employee(String n , String j, int t) {
        this.name= n;
        this.job=j;
        this.salary= t;          
    }

    @Override
    public int hashCode() {      
        return name.hashCode()+job.hashCode()+salary;        
    }

    @Override
    public boolean equals(Object obj) {  
        Employee e = (Employee) obj;    
        return this.name.equals(e.name) && this.job.equals(e.job)
                   && this.salary == e.salary;
    }   
}

2 个答案:

答案 0 :(得分:0)

不确定您在寻找什么。如果您想将员工与密钥(例如,他们的姓名)相关联,您可以这样做:

Map<String, Employee> employeeMap = new HashMap<String, Employee>();

如果要将Employees映射到其他值,您可以执行以下操作:

Map<Employee, MyOtherType> employeeMap = new HashMap<Employee, MyOtherType>();

答案 1 :(得分:0)

如下所示:(?)

Collection<Employee> employees = new LinkedList<Employee>();
Map<String, Collection<Employee>> map = new HashMap<String, Collection<Employee>>();

...........

//Now fill the map as following:
List<Employee> employeesOfTheDepartment = new LinkedList<Employee>();
employeesOfTheDepartment.add(employee);
map.put(employee.getDepartment(), employeesOfTheDepartment);