不可变查询
Immutable Queries
请告诉我重写 equals 和 hashcode 方法是强制性的,即使我使用的密钥是不可变的 class。
例如,我有一个不可变的 class 员工,我想在地图中用作键。我需要重写 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;
}
}
谢谢,
卡马尔
简答:是的,长答:是的;特别是因为 HashMap
和 HashSet
通过文档强制要求。这些是在基于散列的结构内部使用的主要机制。
此外,您应该为您实现Comparable
接口Keys
(如果您使用java-8
)——因为它可能在内部使用以加快您的搜索查询。
不变性对于HashMap的键来说其实是一件非常好的事情。想象一下,您将一个键放入地图(计算哈希码和等于),然后更改它(更改它的 hashcode/equals)并再次搜索它 - 它可能根本找不到。
请告诉我重写 equals 和 hashcode 方法是强制性的,即使我使用的密钥是不可变的 class。
例如,我有一个不可变的 class 员工,我想在地图中用作键。我需要重写 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;
}
}
谢谢, 卡马尔
简答:是的,长答:是的;特别是因为 HashMap
和 HashSet
通过文档强制要求。这些是在基于散列的结构内部使用的主要机制。
此外,您应该为您实现Comparable
接口Keys
(如果您使用java-8
)——因为它可能在内部使用以加快您的搜索查询。
不变性对于HashMap的键来说其实是一件非常好的事情。想象一下,您将一个键放入地图(计算哈希码和等于),然后更改它(更改它的 hashcode/equals)并再次搜索它 - 它可能根本找不到。