用Compsite模式实现树形结构时的堆栈溢出异常

02-11-21 foxprince

我用Composite模式实现树形结构时碰到如下问题:在初始化树时,如果遍历非根节点,并向其上添加孩子节点时总会出现堆栈溢出的错误,具体代码如下:

Public class Composite {

......

protected int id;

protected List children = new ArrayList();

public int getID() {

return this.id;

}

public Iterator getChildren() {

return this.children.iterator();

}

public int getSize() {

return this.children.size();

}

public void add(Composite c) {

try {

this.children.add(c);

} catch (Exception e) {

System.out.println(e.getMessage());

}

}

/**

* Adds a child to the tree.

*

* @param parent the parent to add the new value to.

* @param child new value to add to the tree.

*/

public void addChild(Composite parent, Composite child) {

int parentID = parent.getID();

int childID = child.getID();

if(this.getID() == parentID) {

this.add(child);

}

else {

if(getSize()<1) {

throw new IllegalArgumentException("Parent key " + parentID +

" not found when adding child " + childID + ".");

}

else {

Iterator it = this.getChildren();

Composite node = null;

while(it.hasNext()) {

node = (Composite)it.next();

addChild(node,child);

}

}

}

}

......

}

当执行初始化调用addChild()方法时,总会出现如下异常

java.lang.StackOverflowError, stack: java.lang.StackOverflowError

at java.util.AbstractList$Itr.<init>(AbstractList.java:391)

at java.util.AbstractList$Itr.<init>(AbstractList.java:391)

at java.util.AbstractList.iterator(AbstractList.java:333)

at com.si_tech.nsd.util.tree.Composite.getChildren(Composite.java:101)

at com.si_tech.nsd.util.tree.Composite.addChild(Composite.java:168)

也就是说,对非根节点调用getChildren()方法时发生了堆栈溢出错误,这是为什么???

foxprince
2002-11-22 09:10

大家发现了么?

banq
2002-11-22 11:27

addchild要catch exception

这属于运行的error,你需要具体自己调试。