避免在 toString 方法中递归 [英] Avoiding recursion in toString method
问题描述
这是我在 Java 练习中遇到的巨大问题.所以,我们有这个:
this is my huge mindblowing problem with a Java exercise. So, we've got this:
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate
}
我们的目标是通过切割可能导致递归无穷大的字段来覆盖 toString 方法.最后,它应该看起来像一个带有姓名、年龄、老板和下属的印刷品.
and our goal is to overwrite toString method by cutting fields which may lead to recursive infinity. Finally it's supposed to look like a printed object with a name, age, boss and subordinate.
Employee[age=30,name='Mike',boss=Employee[age=45,name='Ann'], subordinate=[Employee[age=25,name='Jimmy']]]
好吧,我试过了,发现我不知道如何处理 toString 覆盖:
Well, I tried and found that i have no clue how to deal with toString overriding:
import java.util.ArrayList;
import java.util.List;
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
public CyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
CyclicEmployee Mike = new CyclicEmployee(33,"Mike");
Mike.boss = new CyclicEmployee(44,"Ann");
Mike.subordinate = new ArrayList<CyclicEmployee>();
Mike.subordinate.add(new CyclicEmployee(24,"Jim"));
System.out.println(Mike.toString());
}
@Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + boss +
", subordinate=" + subordinate +
'}';
}
}CyclicEmployee{age=33, name='Mike', boss=CyclicEmployee{age=44, name='Ann', boss=null, subordinate=null}, subordinate=[CyclicEmployee{age=24, name='Jim', boss=null, subordinate=null}]}
好像我应该把这里所有的空"字段都删掉,但我找不到出路.
It seems like I should cut all the "null" fields here, but I can't find the way out.
推荐答案
如果我理解正确,您不希望打印空的 CyclicEmployee
对象.您可以检查 boss
和 subordinates
是否为空,然后在 toString()
中跳过它们.因为它们都是相同的类型,所以这个方法对它们都有效.
If I understand correctly, you do not want to print null CyclicEmployee
objects. You can check if boss
and subordinates
are null and then if they are skip them in toString()
. Since all of them are same type, this method will work for all of them.
@Override
public String toString() {
String str = "";
str = "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'';
if (boss != null) {
str += ", boss=" + boss;
}
if (subordinate.size() != 0) {
str += ", subordinate=" + subordinate;
}
str += '}';
return str;
}
这篇关于避免在 toString 方法中递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!