gpt4 book ai didi

java - 用 OR 条件覆盖哈希码

转载 作者:行者123 更新时间:2023-11-29 05:02:44 26 4
gpt4 key购买 nike

我正在写一个 pojo ,我正在覆盖 hashcode 和 equals ,但是我使对象相等的条件是具有 OR 条件。在这种情况下如何编写哈希码???

比如我有一个pojo,有aaa,bbb,ccc三个字段和处理相等的条件是,aaa 必须相等并且 bbb 或 ccc 应该相等。我在等于覆盖部分写了这个但是在这种情况下在哈希码中写什么???

public class POJO {

private String aaa;
private String bbb;
private String ccc;

///How to use or condition here ???????
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aaa == null) ? 0 : aaa.hashCode());
result = prime * result + ((bbb == null) ? 0 : bbb.hashCode());
return result;
}
//my condition is aaa and (bbb or ccc) should be equal
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
POJO other = (POJO) obj;
if (aaa == null) {
if (other.aaa != null)
return false;
} else if (!aaa.equals(other.aaa))
return false;
if (bbb == null || ccc == null) {
if (other.bbb != null || other.ccc != null)
return false;
//This is the main condition
} else if (!bbb.equals(other.bbb) || !ccc.equals(other.ccc))
return false;
return true;
}
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public String getBbb() {
return bbb;
}
public void setBbb(String bbb) {
this.bbb = bbb;
}
public String getCcc() {
return ccc;
}
public void setCcc(String ccc) {
this.ccc = ccc;
}




}

最佳答案

你的equals逻辑不一致,所以你不能定义一致的hashCode

假设您有 3 个具有以下值的对象:

   aaa    bbb  ccc

"a1" "b1" "c1"
"a1" "b1" "c2"
"a1" "b2" "c2"

按照你的逻辑,第一个对象等于第二个(aaa 和 bbb 属性都相等),第二个等于第三个(aaa 和 ccc 属性都相等),但是第一个是不等于第三个(因为 bbb 和 ccc 属性不相等)。 equals 必须是可传递的。

来自Javadoc :

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

关于java - 用 OR 条件覆盖哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31510497/

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