父类卡子类卡java,java递归查询父类下的子类解决办法

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-31 01:49   11   0

Java codeimport java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class StudyMap {

public static void main(String[] args) {

HashMap> result = new HashMap>();

List testList = new ArrayList();

testList.add(new OKBean(1, 0));

testList.add(new OKBean(2, 0));

testList.add(new OKBean(3, 0));

testList.add(new OKBean(4, 1));

testList.add(new OKBean(5, 1));

testList.add(new OKBean(6, 1));

testList.add(new OKBean(7, 2));

testList.add(new OKBean(8, 2));

testList.add(new OKBean(9, 2));

testList.add(new OKBean(10, 4));

testList.add(new OKBean(11, 4));

testList.add(new OKBean(12, 4));

for (OKBean okbean : testList) {

List okbeans = result.get(okbean.getParentId());

if (okbeans == null) {

okbeans = new ArrayList();

result.put(okbean.getParentId(), okbeans);

}

okbeans.add(okbean);

}

displayMap(result, 1, "");

}

public static void displayMap(HashMap> result,

int startKey, String str) {

List list = result.get(startKey);

for (OKBean okBean : list) {

System.out.println(str + okBean.getId() + ":");

if (result.containsKey(okBean.getId())) {

displayMap(result, okBean.getId(), str + " ");

}

}

}

}

class OKBean {

public OKBean() {

}

public OKBean(int id, int parentId) {

this.id = id;

this.parentId = parentId;

}

private int id;

private int parentId;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public int getParentId() {

return parentId;

}

public void setParentId(int parentId) {

this.parentId = parentId;

}

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP