什么问题/陷阱,必须重写时,必须考虑equals和hashCode?
基本上,我正在尝试创建一个独特对象的对象,一组.我有一个很好的想法,就是只使用带有对象的JavaScript对象作为属性名称.如,
set[obj] = true;
Run Code Online (Sandbox Code Playgroud)
这很有效.它适用于字符串和数字,但对于其他对象,它们似乎都"散列"到相同的值并访问相同的属性.是否有某种方法可以为对象生成唯一的哈希值?字符串和数字如何做,我可以覆盖相同的行为吗?
假设我有这个客户端JSON输入:
{
id: "5",
types: [
{id: "1", types:[]},
{id: "2", types:[]},
{id: "1", types[]}
]
}
Run Code Online (Sandbox Code Playgroud)
我有这门课:
class Entity {
private String id;
private Set<Entity> types = new LinkedHashSet<>();
public String getId() {
return this.id;
}
public String setId(String id) {
this.id = id;
}
public Set<Entity> getTypes() {
return types;
}
@JsonDeserialize(as=LinkedHashSet.class)
public void setTypes(Set<Entity> types) {
this.types = types;
}
@Override
public boolean equals(Object o){
if (o == null || !(o instanceof Entity)){
return false;
}
return …Run Code Online (Sandbox Code Playgroud) 我正在学习Kotlin,具有C++和Java背景.我期待以下打印true,而不是false.我知道==那张地图equals.是否默认实现equals比不上每个成员,即firstName和lastName?如果是这样,它不会看到字符串值相等(因为再次==映射equal)?显然,有一些与平等和身份相关的东西,我还没有在Kotlin中找到.
class MyPerson(val firstName: String, val lastName: String)
fun main(args: Array<String>) {
println(MyPerson("Charlie", "Parker") == MyPerson("Charlie", "Parker"))
}
Run Code Online (Sandbox Code Playgroud) 我有一个有4个属性的bean:
user
institutionId
groupId
postingDate
Run Code Online (Sandbox Code Playgroud)
我使用Eclipse生成equals和hashcode,但结果代码并不漂亮.是否有一种紧凑的方式来做同样的事情?假设我希望equals和hashcode使用所有属性或它们的子集.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((groupId == null) ? 0 : groupId.hashCode());
result = prime * result + ((institutionId == null) ? 0 : institutionId.hashCode());
result = prime * result + ((postingDate == null) ? 0 : postingDate.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) …Run Code Online (Sandbox Code Playgroud) 我已经覆盖了 java 对象的 equals 方法。(实际上是 kotlin 中的对象,但它很容易理解,我只是覆盖了 equals 方法)。但现在为了维护 equals 合同,我还应该覆盖 hashcode 方法。但我不知道如何实现适合 equals 方法的哈希码。这是我到目前为止所拥有的:
data class AddressModel(
var id_address: Int = 0,
var id_country: Int = 0,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AddressModel)
return false
else {
if (other.id_address == this.id_address)
return true
}
return false
}
}
Run Code Online (Sandbox Code Playgroud)
编译器强烈建议我覆盖 hashCode 方法。但我不明白要实施什么。在 equals 覆盖中,我只想检查 addressModel 是否与另一个具有相同的 Id,如果是,那么我假设它相等。
这是我到目前为止:
override fun hashCode(): Int {
return Objects.hash(id_address, id_country);
}
Run Code Online (Sandbox Code Playgroud)
但我认为这更好: …