初始化arraylist时发生Java nullpointerException
我尝试使用arraylist元素构建node对象以添加子节点,并成功初始化。但是,当我尝试将节点添加到arraylist时,出现了异常。如何解决这个问题初始化arraylist时发生Java nullpointerException,java,arraylist,Java,Arraylist,我尝试使用arraylist元素构建node对象以添加子节点,并成功初始化。但是,当我尝试将节点添加到arraylist时,出现了异常。如何解决这个问题 public class nodes{ int value=-2; boolean root=false; nodes parent; ArrayList<nodes>Children; public nodes(int value,ArrayList Children) { this.value=value;
public class nodes{
int value=-2;
boolean root=false;
nodes parent;
ArrayList<nodes>Children;
public nodes(int value,ArrayList Children) {
this.value=value;
this.Children=Children;
}
public void setParent(nodes parent) {
this.parent=parent;
}
public void Add(nodes child) {
this.Children.add(child);
}
}
public class TreeHeight {
int n;
int parent[];
nodes Nodes[];
void read() throws IOException {
FastScanner in = new FastScanner();
n = in.nextInt();
ArrayList[]Children=new ArrayList[n];
parent = new int[n];//parent is an array that contains all elements
Nodes=new nodes [n];
for (int i = 0; i < n; i++) {
//parent[i]= ;
//index[i]=i;
Nodes[i]=new nodes(in.nextInt(),Children[i]);
}
//Nodes[0].Add(Nodes[1]);
for (int vertex = 0; vertex < n; vertex++) {
if(Nodes[vertex].value==-1) {Nodes[vertex].root=true;
}
for(int j=0;j<n;j++) {
if(Nodes[j].value==vertex) {
Nodes[j].setParent(Nodes[vertex]);
Nodes[vertex].Add(Nodes[j]);
}
}
}
}
公共类节点{
int值=-2;
布尔根=假;
节点父节点;
ArrayListChildren;
公共节点(int值,ArrayList子节点){
这个。值=值;
这个。孩子=孩子;
}
公共void setParent(节点父节点){
这个。父=父;
}
公共void添加(子节点){
this.Children.add(child);
}
}
公共级树八{
int n;
int父[];
节点[];
void read()引发IOException{
FastScanner in=新的FastScanner();
n=in.nextInt();
ArrayList[]Children=新的ArrayList[n];
parent=new int[n];//parent是包含所有元素的数组
节点=新节点[n];
对于(int i=0;i 对于(int j=0;j我看不到此数组添加值
ArrayList[]Children=new ArrayList[n];
但你在这方面有没有价值
Nodes[i]=new nodes(in.nextInt(),Children[i]);
Children[i]
将始终为空。并且有点偏离主题,但您的代码几乎无法阅读。我建议您开始遵循标准的Java命名和格式约定。感谢您的建议。是否有任何解决方案可以毫无例外地向Children[i]添加节点?添加的Children[i]=new ArrayList();在节点[i]=new nodes之前(in.nextInt(),Children[i]);现在问题已成功解决。您能指定命名和格式问题在哪里吗?@Robby Cornelissensensclass名称应为大写字母;方法、字段和变量名称应为小写字母。其余问题主要是空格使用和缩进问题。获得具有自动格式功能的IDE应该可以解决是的,它们应该在声明后初始化。谢谢。