【发布时间】:2017-03-17 18:34:36
【问题描述】:
我有一个 Tree 实现,但我想将 ArrayList 更改为简单的数组,我不想在 java 中使用集合我只想使用数组,但我不知道如何将 ArrayList 替换为简单的数组。 有一个代码:
public class TreeNode {
private String data = null;
private List<TreeNode> children = new ArrayList<>();
int topSize;// I added it, since i know how is the size of Tree
private TreeNode[] children2 = new TreeNode[topSize];//I added it
private TreeNode parent = null;
public TreeNode(String data) {
this.data = data;
}
int i = 0;//I added it
public void addChild(TreeNode child) {
child.setParent(this);
this.children.add(child);
this.children2[i++] = child;//I added it
}
public void addChild(String data) {
TreeNode newChild = new TreeNode(data);
newChild.setParent(this);
children.add(newChild);
children2[i] = newChild;// I added it
}
public void addChildren(List<TreeNode> children) {
for (TreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<TreeNode> getChildren() {
return children;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
private void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getParent() {
return parent;
}
public static void main(String[] args) {
TreeNode root = new TreeNode("Root");
TreeNode child1 = new TreeNode("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");
TreeNode child2 = new TreeNode("Child2");
child2.addChild("Grandchild3");
root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");
root.addChildren(Arrays.asList(
new TreeNode("Child4"),
new TreeNode("Child5"),
new TreeNode("Child6")
));
TreeNode mainRoot = new TreeNode("MainRoot");
mainRoot.addChildren(Arrays.asList(root));
for (TreeNode node : root.getChildren()) {
System.out.println(node.getData());
}
}
}
我创建 TreeNode[] children2 数组并添加 int topSize,因为我知道树的大小。但它不能正常工作。我想要没有来自 java.java.lang.ArrayIndexOutOfBoundsException 集合的 Tree: 0 in children2[i] = newChild;
【问题讨论】:
-
你面临什么问题? “它不能正常工作”有点太含糊了。
-
我有 :java.lang.ArrayIndexOutOfBoundsException: 0 in children2[i] = newChild;