我在初始化 ArrayList 时遇到了令人沮丧的麻烦。我收到一条错误binaryTreeList.set(1, root);
消息
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.set(Unknown Source)
at BinaryTreeADT.<init>(BinaryTreeADT.java:18)
at Driver.main(Driver.java:7)
我正在尝试使用 ArrayList 实现一个简单的二叉树,我希望“根”元素位于 ArrayList 位置 1。出于某种原因,尽管向所有他们。
这是我按顺序排列的代码Driver
,BinaryTreeADT
并且MyTreeNode
public class Driver {
public static void main(String[] args) {
MyTreeNode mtn = new MyTreeNode(3, 'R');
BinaryTreeADT bt = new BinaryTreeADT(mtn);
bt.printTree();
}
}
二叉树ADT:
import java.util.ArrayList;
import javax.swing.tree.TreeNode;
public class BinaryTreeADT {
private ArrayList<MyTreeNode> binaryTreeList;
private MyTreeNode nullNode = new MyTreeNode(true); //This creates a null node that initially populates the array.
//Constructor with no root
public BinaryTreeADT(){
binaryTreeList = new ArrayList<MyTreeNode>(10);
}
public BinaryTreeADT(MyTreeNode root){
binaryTreeList = new ArrayList<MyTreeNode>(10);
initializeList();
binaryTreeList.set(1, root);
}
private void initializeList(){
for (int i = 0; i < binaryTreeList.size(); i++){
binaryTreeList.add(nullNode);
}
}
public void add(){
}
public void printTree(){
for (int i = 0; i < binaryTreeList.size(); i++){
if (binaryTreeList.get(i) != null)
System.out.println(binaryTreeList.get(i).getNodeChar() + " | ");
}
}
}
我的树节点:
import java.util.Enumeration;
import javax.swing.tree.TreeNode;
public class MyTreeNode implements TreeNode {
private int nodeKey;
private char nodeChar;
private boolean isNull;
public MyTreeNode(int key, char letter){
nodeKey = key;
nodeChar = letter;
}
//Constructor for Null Node
public MyTreeNode(boolean setNull){
isNull = setNull;
}
public boolean isNull(){ //Tells if this is a null node
return isNull;
}
@Override
public Enumeration children() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getAllowsChildren() {
// TODO Auto-generated method stub
return false;
}
@Override
public TreeNode getChildAt(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getChildCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getIndex(TreeNode arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public TreeNode getParent() {
// TODO Auto-generated method stub
return null;
}
public int getNodeKey() {
return nodeKey;
}
public void setNodeKey(int nodeKey) {
this.nodeKey = nodeKey;
}
public char getNodeChar() {
return nodeChar;
}
public void setNodeChar(char nodeChar) {
this.nodeChar = nodeChar;
}
@Override
public boolean isLeaf() {
// TODO Auto-generated method stub
return false;
}
}