gpt4 book ai didi

Java hashCode 应该依赖于最终变量

转载 作者:行者123 更新时间:2023-12-01 10:09:06 26 4
gpt4 key购买 nike

public lass A {
private String id;
private String attr1;
private String attr2;

@Override
public boolean equals(Object obj) {
if (!(obj instanceof A))
return false;

A a = (A) obj;

return new EqualsBuilder()
.append(id, a.id)
.append(attr1, a.attr1
.append(attr2, a.attr2)
.isEquals();
}

@Override
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.hashCode();
}
}

在示例类中,id 应该是最终的,hashCode() 才能正常工作。
否则,在属性修改后,objet 就会从集合中消失,从而导致内存泄漏。

A a = new A();
a.setId("id1");
a.setAttr1("attr1");
a.setAttr2("attr2");

Set set = new HashSet();
set.add(a);

set.contains(a) == true;

a.setId("id2");

set.contains(a) == false;

我错过了什么吗?为什么 HashCodeBuilder javadoc 中没有说明?
这让我陷入困境,因为我见过很多 hashCode 和 equals 在同一组字段上传递的情况。似乎没有人想到属性修改...

    @Override
public boolean equals(Object obj) {
if (!(obj instanceof A))
return false;

A a = (A) obj;

return new EqualsBuilder()
.append(id, a.id)
.append(attr1, a.attr1
.append(attr2, a.attr2)
.isEquals();
}

@Override
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(attr1)
.append(attr2)
.hashCode();
}

最佳答案

它记录在 Object.hashCode 中java文档:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

使用的最终字段可以满足这一点。如果不可能,那么您仍然可以在 hashCode 中使用它们,只要您以后不更改它们的值即可。

关于Java hashCode 应该依赖于最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36260601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com