初始化空值项时出现空指针异常

Mon*_*lal 0 java null nullpointerexception

我想给一个名为State的类的每个子项赋值,而我有一个状态数组最初都为null,我在这里接收空指针引用:

//finding all the neighbor states of a given configuration

public State[] neighborStates(String config, int modeFlag){
    State[] neighborStates=new State[7];
    int i=0;
    for (Operation o : Operation.values()){
        neighborStates[i].config=move(config,o.name().charAt(0));
        neighborStates[i].realCost++;
        neighborStates[i].opSequence+=o.name();
        neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
        i++;
    }       

    return neighborStates;
}
Run Code Online (Sandbox Code Playgroud)

我将代码更改为此但我还是获得了NPE:

public State[] neighborStates(String config, int modeFlag){
        State[] neighborStates=new State[8];
        int i=0;
        for (Operation o : Operation.values()){
            neighborStates[i] = new State(move(config,o.name().charAt(0)),neighborStates[i].realCost++,
                                getHeuristicCost(neighborStates[i].config, modeFlag), neighborStates[i].opSequence+=o.name());
            //neighborStates[i].config=move(config,o.name().charAt(0));
            //neighborStates[i].realCost++;
            //neighborStates[i].opSequence+=o.name();
            //neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
            i++;
        }
Run Code Online (Sandbox Code Playgroud)

类State定义为:

public class State {
    public State(String config, int realCost, int heuristicCost, String opSequence){
        this.config = config;
        this.realCost = realCost;
        this.heuristicCost = heuristicCost;
        this.opSequence = opSequence;
    }
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 7

您需要StateneighborStates数组中实例化.您创建了一个包含7个插槽的阵列,但它们最初都是null.假设你有一个默认的构造函数,它应该看起来像,

for (Operation o : Operation.values()){
  neighborStates[i] = new State();
  // ...
Run Code Online (Sandbox Code Playgroud)

此外,neighborStates基于大小调整可能是一个好主意Operation.values()

State[] neighborStates = new State[Operation.values().length];
Run Code Online (Sandbox Code Playgroud)

  • `getHeuristicCost`在`neighborStates [i]`的初始化中仍然使用`neighborStates [i]`.那时它仍然是空的! (3认同)
  • @MonaJalal我建议为你的类创建getter/setter方法,如果你还没有这样做 - 这样你就可以使用`neighborStates [i] = new State();`,创建`setConfig等方法(String config) ){this.config = config;`,然后使用`neighborStates [i] .getConfig()`或类似的东西检索必要的信息. (2认同)