不可变查询

时间:2017-07-17 06:39:57

标签: hashmap immutability

请让我知道覆盖equals和hashcode方法是强制性的,即使我使用的密钥是不可变类。

例如,我有一个不可变的类Employee,我想在地图中用作键。我是否需要覆盖equals和hashcode方法。

public class Employee  {

    private int empId;
    private String name;

    public Employee(String name, int empId) {

       this.empId = empId;
       this.name=name;
    }

    public int getEmpId() {
       return empId;
    }
    public String getName() {
       return name;
    }
}

谢谢, 哈拉

1 个答案:

答案 0 :(得分:0)

简短回答:是的,答案很长:yeeeeees;特别是因为HashMapHashSet通过文档强制执行。这些是在基于散列的结构内部使用的主要机制。

此外 应为您实现Comparable界面Keys(如果您使用java-8) - 因为这可能会在内部用于加速您的Map<String, ItemVO> itemChildMap = new LinkedHashMap<String, ItemVO>(); ItemVO item1 = new ItemVO("98091", "Red"); ItemVO item2 = new ItemVO("32456", "Black"); ItemVO item3 = new ItemVO("12323", "Green"); ItemVO item4 = new ItemVO("78956", "Red"); ItemVO item5 = new ItemVO("11231", "Green"); ItemVO item6 = new ItemVO("10098", "Black"); ItemVO item7 = new ItemVO("23410", "Red"); itemChildMap.put("98091", item1); itemChildMap.put("32456", item2); itemChildMap.put("12323", item3); itemChildMap.put("78956", item4); itemChildMap.put("11231", item5); itemChildMap.put("10098", item6); itemChildMap.put("23410", item7); 搜索查询。

对于HashMap键,不变性实际上是一件非常好的事情。想象一下,你把一个键放入地图(哈希码和等于计算),然后你改变它(改变它的哈希码/等号)并再次搜索它 - 它可能根本找不到。