gpt4 book ai didi

java - 如何从包含自己数组的对象数组中获取n条记录

转载 作者:行者123 更新时间:2023-12-02 09:46:31 26 4
gpt4 key购买 nike

我想要 n 个数字,这意味着我的 ArrayList 的最后一条记录,但问题是我的 ArrayList 是自定义 POJO 类,它包含自己的数组,这就是为什么我无法识别 ArrayList 包含多少条记录

请检查下面我正在创建 POJO 类的 JSON

{
"data": [
{
"id": "7",
"name": "Grand Father Name",
"parent_id": "0",
"relation_type": "grand-father",
"children": [

]
},
{
"id": "8",
"name": "Grand Mother Name",
"parent_id": "0",
"relation_type": "grand-mother",
"children": [
{
"id": "9",
"name": "Father Name",
"parent_id": "8",
"relation_type": "father",
"children": [
{
"id": "11",
"name": "My Name",
"parent_id": "9",
"relation_type": "self",
"children": [

]
}
]
},
{
"id": "10",
"name": "Mother Name",
"parent_id": "8",
"relation_type": "mother",
"children": [

]
}
]
}
]
}

POJO类

public class Tree {
@SerializedName("data")
@Expose
public ArrayList<Child> data = null;

public class Child {
@SerializedName("family_id")
@Expose
public int family_id;
@SerializedName("name")
@Expose
public String name;
@SerializedName("relation_type")
@Expose
public String relation_type;
@SerializedName("parent_id")
@Expose
public int parentId;
@SerializedName("children")
@Expose
public List<Child> children = null;

public int getId() {
return family_id;
}

public void setId(int id) {
this.family_id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getParentId() {
return parentId;
}

public void setParentId(int parentId) {
this.parentId = parentId;
}

public List<Child> getChildren() {
return children;
}

public void setChildren(List<Child> children) {
this.children = children;
}
}
}

如您所见,Child 类包含一个自己的列表,因此我无法确定该列表将包含多少条记录

希望它能解决我的问题,任何帮助将不胜感激。提前致谢

最佳答案

您可以递归地执行此操作:

ArrayList<Child> list = new ArrayList<>(); //this is the list where you want to fill all children

void fillRecursively(ArrayList<Child> root){
List<Child> children = root.getChildren();
for(Child child : children){
if(child.getChildren().size()!=0){
fillRecursively(child);
}else{
list.add(child);
}
}
}
}

另外,不要忘记将根节点添加到列表中。

list.add(root); //at the beginning

关于java - 如何从包含自己数组的对象数组中获取n条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56611093/

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