我定义了两个类,以便它们都包含对另一个对象的引用。它们看起来与此类似(这是简化的;在我的实际域模型中,类A包含一个B列表,每个B都有对父A的引用):
public class A {
public B b;
public String bKey;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((b == null) ? 0 : b.hashCode());
result = prime * result + ((bKey == null) ? 0 : bKey.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof A))
return false;
A other = (A) obj;
if (b == null) {
if (other.b != null)
return false;
} else if (!b.equals(other.b))
return false;
if (bKey == null) {
if (other.bKey != null)
return false;
} else if (!bKey.equals(other.bKey))
return false;
return true;
}
}
public class B {
public A a;
public String aKey;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((aKey == null) ? 0 : aKey.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof B))
return false;
B other = (B) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (aKey == null) {
if (other.aKey != null)
return false;
} else if (!aKey.equals(other.aKey))
return false;
return true;
}
}
在hashCode与equals已通过使用Eclipse中A和B这两个问题的两个场产生的是调用equals或hashCode在任一对象方法的结果在StackOverflowError因为它们都调用另一个对象的equals和hashCode方法。例如,以下程序将无法StackOverflowError使用上述对象:
public static void main(String[] args) {
A a = new A();
B b = new B();
a.b = b;
b.a = a;
A a1 = new A();
B b1 = new B();
a1.b = b1;
b1.a = a1;
System.out.println(a.equals(a1));
}
如果用这种方式用循环关系定义域模型存在内在的错误,请告诉我。据我所知,虽然这是相当普遍的情况,对吗?
什么是确定的最佳实践hashCode,并equals在这种情况下?我想将所有字段都保留在equals方法中,这样就可以对对象进行真正的深度相等比较,但是我看不到如何解决这个问题。谢谢!