gpt4 book ai didi

java - 根据传递的参数从树中获取选定的对象

转载 作者:行者123 更新时间:2023-11-30 06:23:07 25 4
gpt4 key购买 nike

所以我有这个 Person 对象。每个人都有人员对象列表等等..

public class Person {
....
private List<Person> people = new ArrayList<>();

....

public List<Person> getPeople() {
return people;
}

public void setPeople(List<Person> people) {
this.people = people;
}

enter image description here

我已经使用以下代码得到了最大部门答案,答案是我得到的负1

public static int maxDepth(Person p) {
int maxChildrenDepth = 0;
for (Person c: p.getPeople()) {
maxChildrenDepth = Math.max(maxChildrenDepth, maxDepth(c));
}
return 1 + maxChildrenDepth;
}

所以如果我将 Person 对象和 int 传递到方法中,比如说 getPersonLevel(List allPerson, 1) ,我应该获取列表中蓝色框内的所有 Person 对象,如果我输入 2,我应该获取所有对象在红色框的列表中等等,具体取决于 int 参数..我该如何实现?任何帮助表示赞赏。

最佳答案

为什么不将 person 作为方法的参数传递,为什么不创建 Person 类的 maxDepthgetPersonLevel 方法?

结果你会得到:

public class Person {

private Set<Person> people = new HashSet<>();

public Set<Person> getPeople() {
return people;
}

public void setPeople(Set<Person> people) {
this.people = people;
}

public int maxDepth() {
int maxChildrenDepth = 0;
for (Person prs : people) {
maxChildrenDepth = Math.max(maxChildrenDepth, prs.maxDepth());
}
return 1 + maxChildrenDepth;
}

public Set<Person> getPersonLevel(int depth) {
Set<Person> ppl = new HashSet<>();
ppl.addAll(gatherEmployees(ppl, depth));
return ppl;
}

private Set<Person> gatherEmployees(Set<Person> ppl, int depth) {
if (depth - 1 > 0 && people != null) {
people.forEach(prs -> ppl.addAll(prs.gatherEmployees(ppl, depth - 1)));
}
return people;
}
}

关于java - 根据传递的参数从树中获取选定的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47734129/

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