Object数组导致NullPointerException Java

ciy*_*iyo 0 java nullpointerexception

我不知道为什么,但这行代码给出了一个NullPointerException.我搜索了创建用户obj的数组.在Java中,但是,我找不到任何问题.

private State[] states;
.    
.
.
private void initializeStates( )
        {
            states = new State[ stateNames.length ]; // Throws NullPointerException

        for( int i = 0; i < stateNames.length; i++ )
        {
            states[i] = new State();
            states[i].setName( stateNames[i] );
            states[i].setColor( stateColors.getColor() );
        }
    } // End of initializeStates()
Run Code Online (Sandbox Code Playgroud)

这是班级:

public class State
{
    private String stateName;
    private String color;
    private boolean isStartState;
    private boolean isFinalState;

        State()
        {
            stateName = new String(); // Can this line cause nullPtrException?
            color = new String(); // Can this line cause nullPtrException?
            isStartState = false;
            isFinalState = false;
        }

        public void setName( String name ){ stateName = name; }
        public void setColor( String clr ) {   color = clr; }
        public void makeStart( ) {  isStartState = true; }
        public void makeFinal( ) {  isFinalState = true; }

    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

如果此行抛出异常:

states = new State[ stateNames.length ]; // Throws NullPointerException
Run Code Online (Sandbox Code Playgroud)

......那么问题就在stateNames于此null.你没有像其他任何代码那样做到这一点.

您尚未显示stateNames声明或初始化的位置,但这是您应该查看的位置.

顺便说一下,这个:

stateName = new String();
Run Code Online (Sandbox Code Playgroud)

......无缘无故地效率低下.只需使用空字符串文字:

stateName = "";
Run Code Online (Sandbox Code Playgroud)

(或者更好的是,将适当的初始值作为构造函数参数.)