如何在Java中构造二维数组?

Kes*_*hab 1 java constructor multidimensional-array

我被困在一个非常简单的问题超过2个小时.我正在尝试创建一个二维数组并用构造函数填充它.但是,我无法通过这一步.

public class Test
{    
     public State [][] test1= new State[4][3];//
     public State test2[][]= new State[4][3];//
     public State [][]test3;
     public State test4[][];

     public class State{
         int position;
         double reward;
         int policy;
     }

     public Test(){
            test1[1][1].position=1; // never worked
            test2[1][3].position=2; //never worked
            test3=new State[4][3];
            test3[1][2].position=3; //never worked
            test4=new State[4][3];
            test4[2][2].position=4;//never worked
     }
}
Run Code Online (Sandbox Code Playgroud)

我用以下代码调用上面的函数

Test test= new Test();
Log.e("done","pass"); //I never reach here. the code always stuck on the constructor.
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 6

创建数组时:

public State [][] test1 = new State[4][3];
Run Code Online (Sandbox Code Playgroud)

您正在创建一个可以容纳4*3个State实例的数组,但是数组中的每个位置都被初始化为null.

State在访问数组之前,您需要为数组中的每个位置分配一个实例.如果你不这样做,你会得到一个NullPointerException.

例如 :

public Test()
{
    test1[1][1] = new State();
    test1[1][1].position = 1;
    ....
}
Run Code Online (Sandbox Code Playgroud)