有没有办法在Java中手动重新哈希映射?

我有一个Employee具有两个属性的类。


public class Employee {


    private int empId;

    private String empName;


    public int getEmpId() {

        return empId;

    }


    public void setEmpId(int empId) {

        this.empId = empId;

    }


    public String getEmpName() {

        return empName;

    }


    public void setEmpName(String empName) {

        this.empName = empName;

    }


    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (!(o instanceof Employee)) return false;

        Employee employee = (Employee) o;

        return getEmpId() == employee.getEmpId() &&

                Objects.equals(getEmpName(), employee.getEmpName());

        //return Objects.equals(getEmpName(), employee.getEmpName());

    }


    @Override

    public int hashCode() {

        //return Objects.hash(getEmpId());

        return Objects.hash(getEmpId(), getEmpName());

    }

}

我使用此类作为 Hashmap 中的键。


现在,当我修改原始对象(emp在这种情况下更改员工对象的名称)时,我无法访问最初保存在地图中的条目。只有当我将名称回滚到原始值时,我才能再次访问该对象。


这表明,当我更改 Employee 对象中的名称时,它的哈希值已更改,并且未存储在 Hashmap 中的正确存储桶下。


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


        // Set Employee with Name Shashi

        Employee emp = new Employee();

        emp.setEmpId(1);

        emp.setEmpName("Shashi");


        // Add to Map

        map.put(emp, emp.getEmpName());


        // Modify The Original Employee object's Name

        emp.setEmpName("Shashi Bhushan");


        // This object does not exist as key in map now

        Assert.assertFalse(map.containsKey(emp));


        // Create object with same name(used when creating)

        Employee similarEmployee = new Employee();

        similarEmployee.setEmpId(1);

        similarEmployee.setEmpName("Shashi");



解决能够在映射中获取对象的问题的一种解决方案是使 Employee 类不可变。


我能想到的另一个理论解决方案是重新散列映射并将修改后的员工对象保留在映射中正确的存储桶中,但我在散列映射中看不到任何重新散列它的方法。请建议我是否朝着正确的方向思考,或者是否有其他解决方案。


PS这一切都是为了理解hashmap,所以对于如何解决这个问题没有限制。


白猪掌柜的
浏览 51回答 1
1回答

FFIVE

我认为empId可以唯一标识一个员工。soequals和hashCode方法只需要处理empId字段:&nbsp; &nbsp;@Override&nbsp; &nbsp; public boolean equals(Object o) {&nbsp; &nbsp; &nbsp; &nbsp; if (this == o) return true;&nbsp; &nbsp; &nbsp; &nbsp; if (!(o instanceof Employee)) return false;&nbsp; &nbsp; &nbsp; &nbsp; Employee employee = (Employee) o;&nbsp; &nbsp; &nbsp; &nbsp; return getEmpId() == employee.getEmpId());&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public int hashCode() {&nbsp; &nbsp; &nbsp; &nbsp; return Objects.hash(getEmpId());&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java