java递归构建菜单树

 package testSimple;

 import java.util.ArrayList;
import java.util.List; public class BuildTree {
public static void main(String[] args) {
List<Tree> list = new ArrayList<Tree>();
list.add(new Tree(1, "一级菜单", 0));
list.add(new Tree(2, "二级菜单1", 1));
list.add(new Tree(3, "二级菜单2", 1));
list.add(new Tree(4, "二级菜单3", 1));
list.add(new Tree(5, "三级菜单11", 2));
list.add(new Tree(6, "三级菜单12", 2));
list.add(new Tree(7, "三级菜单21", 3));
list.add(new Tree(8, "三级菜单22", 3));
list.add(new Tree(9, "三级菜单31", 4));
list.add(new Tree(10, "三级菜单32", 4)); List<Tree> result = buildTree(list, 0);
System.out.println(result);
} public static List<Tree> buildTree(List<Tree> list, int fid) {
List<Tree> resultList = new ArrayList<Tree>();
if (list == null || list.size() == 0 || fid < 0) {
return null;
}
for (Tree tree : list) {
if (tree.getFid() == fid) {
resultList.add(tree);
tree.setChildren(buildTree(list, tree.getId()));
}
}
return resultList;
} } class Tree {
private int id;
private String name;
private int fid;
private List<Tree> children; public Tree(int id, String name, int fid) {
super();
this.id = id;
this.name = name;
this.fid = fid;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getFid() {
return fid;
} public void setFid(int fid) {
this.fid = fid;
} public List<Tree> getChildren() {
return children;
} public void setChildren(List<Tree> children) {
this.children = children;
} }
上一篇:ajax删除DB数据


下一篇:FTP客户端连接时中文乱码问题处理