简体   繁体   English

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

[英]How to get value from HashMap depending on key name, while we are passing custom class objects as key and value

How to get value from Hash Map depending on key name, while we are passing custom class objects as key and value pair.In below code while i am using get method to retrieve the value by using key , i am getting compile time error. 当我们将自定义类对象作为键和值对传递时,如何根据键名从哈希映射中获取值。在下面的代码中,当我使用get方法通过键检索值时,我遇到了编译时错误。 Please help me regarding this. 请帮助我。

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);

Department.java- 部门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- 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;
}
}

I want to retrieve all the details of employee by passing either department id or deptname 我想通过传递部门ID或部门名称来检索员工的所有详细信息

You have to override the equals method of Employee class then you can use 您必须重写Employee类的equals方法,然后才能使用

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

If you are going to use some class as key in HashMap or HashSet you need to add methods equals() and hashCode() to it. 如果要在HashMap或HashSet中将某些类用作键,则需要向其添加equals()和hashCode()方法。 Like: 喜欢:

public static 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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee1 employee1 = (Employee1) o;

        if (age != employee1.age) return false;
        if (id != employee1.id) return false;
        if (salary != employee1.salary) return false;
        if (!name.equals(employee1.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        result = 31 * result + (int) (salary ^ (salary >>> 32));
        return result;
    }
}

And after it will be possible to find value by new key like here: 之后,可以像下面这样通过新键来寻找价值:

public static void main(String[] args) throws Exception {
    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 = hm.get(new Employee1(0, "name5", 28, 15000));
    System.out.println(value);
}

And if you need to execute System.out.println(value); 并且如果您需要执行System.out.println(value); You need to add method toString() to Department1. 您需要将toString()方法添加到Department1。 Like: 喜欢:

    @Override
    public String toString() {
        return "Department1{" +
                "deptid=" + deptid +
                ", deptname='" + deptname + '\'' +
                '}';
    }

Check the bellow classes for getting result. 检查波纹管类以获得结果。

MainTest.java MainTest.java

import java.util.HashMap;

/**
* @author Rajesh
*
*/
public class MainTest {

public static void main(String []args)
{
    HashMap<Employee, Department> hm= new HashMap<Employee, Department>();
    hm.put(new Employee(0, "name0", 20, 46666), new Department(0, "developer"));
    hm.put(new Employee(0, "name0", 25, 46666), new Department(0, "tester"));
    hm.put(new Employee(0, "name3", 34, 3000), new Department(0, "hr"));
    hm.put(new Employee(0, "name4",40, 26666), new Department(0, "manager"));
    hm.put(new Employee(0, "name5",28, 15000), new Department(0, "accountant"));
    Department value = (Department) hm.get(new Employee(0, "name3", 34, 3000));
    System.out.println(value);

}
}

//Common class for getting object value //获取对象值的通用类

MainData.java MainData.java

/**
* @author Rajesh
*
*/

import java.lang.reflect.Field;

public class MainData<E> {

Class c;
public String toStringData(E e1) {
    // TODO Auto-generated method stub
    StringBuffer getData= new StringBuffer();
    try {
        c=e1.getClass();;
         Field fields[] = c.getDeclaredFields();
         for (Field field : fields) {
             Object fieldValue = field.get(e1);
             getData.append(field.getName()+":"+fieldValue+",");
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return getData.toString();
}
}

Department.java 部门.java

/**
* @author Rajesh
*
*/

public class Department extends MainData<Department> {

public int deptid;
public String deptname;
public int getDeptid() {
    return deptid;
}
public void setDeptid(int deptid) {
    this.deptid = deptid;
}
public String getDeptname() {
    return deptname;
}
public void setDeptname(String deptname) {
    this.deptname = deptname;
}
public Department(int deptid, String deptname) {
    this.deptid = deptid;
    this.deptname = deptname;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    //for getting object value
    return super.toStringData(this);
}


}

Employee.java Employee.java

/**
* @author Rajesh
*
*/

public class Employee {

private int id;
private String name;
private int age;
private long salary;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public long getSalary() {
    return salary;
}
public void setSalary(long salary) {
    this.salary = salary;
}
public Employee(int id, String name, int age, long salary) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.salary = salary;
}

@Override
public boolean equals(Object obj) {
    Employee employee = (Employee) obj;
    //compare all the property 
    if (this.age != employee.age) return false;
    if (this.id != employee.id) return false;
    if (this.salary != employee.salary) return false;
    if (!this.name.equals(employee.name)) return false;
    return true;
}

@Override
public int hashCode() {
    //return any unique code
    return this.id+this.name.hashCode()+this.age+(int)this.salary;
}


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM