我在创建和使用对象输入时遇到问题List<Integer>.当我运行以下代码时,我得到一个NullPointerException因为Object没有初始化.
import java.util.List;
public class RBTree {
public static class Tree {
public List<Integer> parent;
public List<Integer> right;
public List<Integer> left;
public List<Integer> data;
public List<Boolean> black;
}
public static void main (String[] args){
Tree rb =new Tree();
rb.data.add(-1);
rb.left.add(-1);
rb.right.add(-1);
rb.parent.add(-1);
rb.black.add(Boolean.TRUE);
}
}
Run Code Online (Sandbox Code Playgroud)
编译器也给我错误,除非我添加static到public static class Tree行,但我不想Tree是static不可变的.我需要能够struct在C中使用或多或少的树.
使用此代码,我尝试将包含数据的文件加载到对象数组中.我没有正确地对象中的字段,因为当我运行此代码时,我得到一个NullPointerException.数组在那里,甚至是正确的大小,但字段没有初始化.我该怎么解决这个问题?
这是代码:
public class aJob {
public int job;
{
job = 0;
}
public int dead;
{
dead = 0;
}
public int profit;
{
profit = 0;
}
}
public class Main {
public static void main(String[]args) throws IOException {
File local = readLines();
Scanner getlength = new Scanner(local);
int lines = 0;
while (getlength.hasNextLine()) {
String junk = getlength.nextLine();
lines++;
}
getlength.close();
Scanner jobfile = new Scanner(local); // check if empty
aJob list[] = new aJob[lines];
aJob …Run Code Online (Sandbox Code Playgroud)