java - 如何从包含自己的数组的对象数组中获取n条记录
问题描述
我想要 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;
}
}
}
如您所见,子类包含自己的列表,因此我无法确定该列表将包含多少条记录
希望它能解决我的问题,任何帮助将不胜感激。提前致谢
解决方案
您可以递归地执行此操作:
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 - 为什么使用以下程序在 Eclipse 的控制台中没有得到任何响应?
- asp.net - ASP.NET_SessionId cookie 在特定服务器上的请求之间消失
- export - 如何避免导出 org-mode header 标题
- c++ - 调用 moveToThread 后 QSound::play 不起作用
- powershell - 将变量传递给流的实验
- sql - 从第一天到昨天计算当前月份的天数
- reactjs - react-hightchart:event.point 中的所有值都为空
- reactjs - Antd列标题中的Unicode字符?
- python - Pandas 将字典列表(GA 输出)转换为有意义的数据帧
- cmake - 如何在不删除和重新创建构建目录的情况下从头开始重新运行 CMake