构建树对象封装信息(一)

2014-11-24 10:09:12 · 作者: · 浏览: 0
package com.wangjin.domaintree;
public class NodeSource {
private int id;
private int parentid;
private String title;
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;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public NodeSource(int id, int parentid, String title) {
super();
this.id = id;
this.parentid = parentid;
this.title = title;
}
public NodeSource() {
super();
}


}

package com.wangjin.domaintree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TreeNode {
// 节点携带的值
private Map tag;
// 儿子节点
private List nodes;
/** 节点信息键值对,该属性不会为空指针,但可能没有键值对存在[就是map.size()==0] */
public Map getTag() {
if (tag == null)
tag = new HashMap();
return tag;
}
public void setTag(Map tag) {
this.tag = tag;
}
/** 获得所有子节点,该属性不会为空指针,但可能没有集合元素存在 */
public List getNodes() {
if (nodes == null)
nodes = new ArrayList();
return nodes;
}
public void setNodes(List nodes) {
this.nodes = nodes;
}
public TreeNode(Map tag, List nodes) {
super();
this.tag = tag;
this.nodes = nodes;
}
public TreeNode() {
super();
}
public TreeNode(Map tag) {
super();
this.tag = tag;
}
}
package com.wangjin.domaintree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CapsulationTree {
public TreeNode getTree() {
//用一个集合模拟数据表的内容,也就是一下集合的内容完全可以查询自 数据库
List treeList = new ArrayList();
treeList.add(new NodeSource(0,-1,"root"));
treeList.add(new NodeSource(1,0,"node1"));
treeList.add(new NodeSource(2,1,"node2"));
treeList.add(new NodeSource(3,1,"node3"));
treeList.add(new NodeSource(4,0,"node4"));
treeList.add(new NodeSource(5,4,"node5"));
treeList.add(new NodeSource(6,4, "node6"));
treeList.add(new NodeSource(7,5,"node7"));
treeList.add(new NodeSource(8,5,"node8"));
treeList.add(new NodeSource(9,7, "node9"));
treeList.add(new NodeSource(10,7,"node10"));

//将这个从集合封装成TreeNode
//构造一个根节点
TreeNode rootNode = new TreeNode();
rootNode.getTag().put("id", "0");
rootNode.getTag().put("title", "root");


//将这个集合封装成Map
Map treeNodeMap = new HashMap();
//下面的循环完成两个功能:
// 1.将所有对象封装成Map里面的键值对,且值是TreeNode类型
// 2.将没有父节点的TreeNode添加到根节点rootNode
for(NodeSource nodeSource:treeList){
TreeNode node = new TreeNode();
node.getTag().put("id",((Integer)nodeSource.getId()).toString());
node.getTag().put("title", nodeSource.getTitle());
treeNodeMap.put(((Integer)nodeSource.getId()).toString(),node);
System.out.println("("+nodeSource.getId()+","+nodeSource.getParentid()+")");
if (nodeSource.getParentid()==-1){//如果没有父节点则添加到根节点
rootNode.getNodes().add