J2ME树形结构实现
|
|
Author: Wupei | Date: 2009-04-26 |
View: 2762 |
J2ME开发 - 程序设计 | Digg:
2
|
|
树形结构(tree)是比较常用的数据结构了,MIDP中没有它的身影,不然我就不用写这篇文章了。 代码如下: /** * * @author hunhun1981 */ public class HTree { private HNode root; private HNode current; private int currDepth; private int maxDepth; public HTree(Object rootValue) { root = new HNode(null, rootValue); current = root; } public void goRoot() { current = root; currDepth = 0; } public boolean goChild(int index) { if (current.childList != null) { if (current.childList.size() > 0 && index < current.childList.size()) { current = (HNode) current.childList.elementAt(index); currDepth++; if (currDepth > maxDepth) { maxDepth = currDepth; } return true; } } return false; } public void goBack() { if (current.father != null) { current = current.father; currDepth –; } } public Object getCurrent() { return current.value; } public int getCurrentDepth() { return currDepth; } public int getMaxDepth() { return maxDepth; } public Object[] getChilds() { if (current.childList != null) { if (current.childList.size() > 0) { Object[] ret = new Object[current.childList.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = ((HNode) current.childList.elementAt(i)).value; } return ret; } } return null; } public Object getChild(int index) { if (current.childList != null) { if (current.childList.size() > 0 && index < current.childList.size()) { return ((HNode) current.childList.elementAt(index)).value; } } return null; } public void addChild(Object obj) { if (current.childList == null) { current.childList = new Vector(); } current.childList.addElement(new HNode(current, obj)); } public void addChilds(Object[] objs) { if (current.childList == null) { current.childList = new Vector(); } for (int i = 0; i < objs.length; i++) { current.childList.addElement(new HNode(current, objs[i])); } } public int hasChild() { if (current.childList == null || current.childList.size() <= 0) { return 0; } else { return current.childList.size(); } } private class HNode { public Vector childList; public HNode father; public Object value; public HNode(HNode father, Object value) { this.value = value; this.father = father; this.childList = null; } } }这个类实现简单,没有包含复杂的功能,仅仅用来做树形数据的存储还是不错的。比如游戏中用来管理场景,管理资源;应用中用来作分类数据的表现等等。完全足以胜任。 使用方法如下: 总之,我比较倾向于简单实现,希望它不太让人觉得简陋就好。从实用出发,它还是能够满足大部分受限平台的需求的。 转自: hunhun1981的专栏 。
更多阅读: |
尚无评论发表