EdwardWong 2006-11-07
把id,parentId,name,url结构的二维信息转换为内存中的树型结构对象
java类:
Node为容器接口,定义容器的规则
TreeNode为Node容器的实现类,有自己内部的存储结构
NodeService为对容器操作的接口
NodeLoader类通过NodeService类填充容器数据
public interface Node { public String getId(); public String getParentId(); public Node[] getChild(); public Object getValue(); public void setId(String id); public void setParentId(String parentId); public void setChildNode(Node[] childNode); public void setValue(Object object); } public class TreeNode implements Node { private String id; private String parentId; private Node[] childNode; private Object value; //geters, setters methods } public interface NodeService { public Node getRoot(); public Node[] getChild(Node node); } public class NodeLoader { NodeService nodeService ; public Node load(NodeService nodeService) { this.nodeService = nodeService ; Node node = nodeService.getRoot(); setChild(node); return node; } private void setChild(Node node) { Node[] childNode = nodeService.getChild(node); node.setChildNode(childNode); if (null == childNode) { return; } for (int i = 0; i < childNode.length; i++) { setChild(childNode[i]); } } }
以菜单树型结构数据为例
Menu为具体的数据结构,作为Node的Object类型的value
MenuNodeService为NodeService接口的实现
public class Menu { private String name ; private String url ; private String description ; private String order ; //geters, setters methods public class MenuNodeService implements NodeService{ public Node getRoot(){ Node rnode = MenuDao.getRootNode(); return rnode ; } public Node[] getChild(Node node){ Node[] rnodes = MenuDao.getChildNode(Node node); return rnodes ; } }
测试代码
public class TestMenuTree { public static void main(String[] args){ NodeLoader loader = new NodeLoader(); NodeService nodeSerive = new MenuNodeService(); Node node =loader.load(nodeSerive); print(node); } public static void print(Node node){ if(node.getChild() == null || node.getChild().length == 0) return ; for(int i = 0 ; i<node.getChild().length ; i ++){ log(((Menu)(node.getChild()[i].getValue())).getName()); print(node.getChild()[i]); } } public static void log(String s){ System.out.println(s); } }
希望大家提出意见,提高扩展性和执行效率
之前提到去除一维数组中的重复元素用unique()函数,如果要去除二维数组中的重复行该怎么操作呢?list2=list必须先把列表中每个元素转化为tuple,因为list不可哈希但是tuple可哈希。