gpt4 book ai didi

java - 如何为两个互相指向的对象编写 toString

转载 作者:太空宇宙 更新时间:2023-11-04 14:55:33 24 4
gpt4 key购买 nike

class A {
String one;
String two;
B bRef;
Collection<B> bCollRef;

A(String one, String two)
{
this.one = one;
this.two = two;
}

//setters for bRef and bCollRef;
}

class B {
String three;
A a;

B(String three)
{
this.three = three;
}

//setter for a
}

A a1 = new A(...);
A a2 = new A(...);
a1.setbRef(new B(str,a2));
a2.setbCollRef(new B(str,a1));

a2 就像 a1 的子级,a1 是 a2 的父级。为这些类编写 toString 方法并避免 stackoverflow 错误的最佳方法是什么。

最佳答案

假设您有一个用于 B 中的 A 引用的公共(public)访问器,这将起作用

class A {
String one;
String two;
B bRef;
Collection<B> bCollRef;

A(String one, String two)
{
this.one = one;
this.two = two;
}

//setters for bRef and bCollRef;

@Override
public void toString(){

if(bRef.geta() == this)
//you have a circular reference, dont step into it(don't call the next toString() method) and you won't stackoverflow here
else
//no circular reference, no problems here, tostring it as you will

}
}

现在,如何编写 toString() 方法取决于您希望如何将对象转换为字符串...这个简单的 if 语句将保护您免受循环引用的影响。如果您有更多可能使事情复杂化的引用,我建议您退后一步并重新思考您是如何做事的,您的对象不应该需要看到所有其他对象。

如果您确实有高阶循环引用情况,并且有引用b1b2,例如a1 -> b1 -> a2 -> b2 -> a1 你需要编写这样的代码..但在实践中你需要非常小心空引用:

    @Override
public String toString(){
//do tostring stuff on current object
A nextA = bRef.geta();
//do tostring stuff on next stuff

while(nextA != this){
nextA = nextA.getbRef.getA();
//unravel the references until you come around full-circle
}

}

关于java - 如何为两个互相指向的对象编写 toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23254330/

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