java循环着重复引用对象_在Java中为具有循环引用的对象实现equals和hashCode

我定义了两个类,以便它们都包含对另一个对象的引用。它们看起来与此类似(这是简化的;在我的实际域模型中,类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方法中,这样就可以对对象进行真正的深度相等比较,但是我看不到如何解决这个问题。谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值